首页 > 解决方案 > SQL 查询返回同一表中子组内至少一列匹配的所有记录

问题描述

messages 在 postgresql 中有一个表,其中每条记录都是一条带有字段的消息:id, session_creation_time, customer_id, message 我首先需要将消息分组session_creation_timecustomer_id这样我就可以找出哪些消息属于同一会话会话的一部分,这样我就可以执行以下操作:

SELECT * 
FROM messages 
GROUP BY session_creation_time, customer_id, id 
ORDER BY session_creation_time

之后,我需要返回按 session_creation_time 和 customer_id 分组的所有消息,其中至少有一条消息与我的运营商匹配message ilike "%myString%"

有任何想法吗?

样本数据

-----------------------------------------------------------------------
id  |session_creation_time| customer_id | msg_to | msg_from | message |    
----|---------------------|-------------|--------|----------|---------|
1   | 2019-10-22 14:43:04 | a           |   a    |   me     | hello   |
----|---------------------|-------------|--------|----------|---------|
2   | 2019-10-22 14:43:04 | a           |   me   |   a      | hi      |
----|---------------------|-------------|--------|----------|---------|
3   | 2019-10-21 14:43:04 | b           |   me   |   b      |ru there?|
----|---------------------|-------------|--------|----------|---------|
4   | 2019-10-21 14:43:04 | b           |   b    |  me      |   yes   |
----|---------------------|-------------|--------|----------|---------|
5   | 2019-10-21 14:43:04 | b           |   me   |   b      | help pls|
----|---------------------|-------------|--------|----------|---------|
6   | 2019-10-21 14:43:04 | b           |   b    |  me      |I'll help|
----|---------------------|-------------|--------|----------|---------|
7   | 2019-10-25 14:43:04 | b           |   me   |   b      |hi its'me|
----|---------------------|-------------|--------|----------|---------|
8   | 2019-10-25 14:43:04 | b           |   b    |  me      |welcome  |
----|---------------------|-------------|--------|----------|---------|

预期结果

如果我的操作员是message ilike '%help%'我的查询应该返回 id 为 : 3,4,5,6 的消息,因为这些消息是来自同一对session_creation_time`` andcustomer_id where at least one of the messages has the stringhelp``` 的消息。并忽略其余的消息

标签: sqlpostgresqlsubquery

解决方案


您必须指定需要分组结果的列,然后包含过滤行的条件,如下所示

SELECT COUNT(customer_id), customer_id, session_creation_time FROM messages WHERE message LIKE '%somestring%' GROUP BY session_creation_time, customer_id ORDER BY session_creation_time


推荐阅读