sql - SQL 查询返回同一表中子组内至少一列匹配的所有记录
问题描述
我 messages
在 postgresql 中有一个表,其中每条记录都是一条带有字段的消息:id, session_creation_time, customer_id, message
我首先需要将消息分组session_creation_time
,customer_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`` and
customer_id where at least one of the messages has the string
help``` 的消息。并忽略其余的消息
解决方案
您必须指定需要分组结果的列,然后包含过滤行的条件,如下所示
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
推荐阅读
- php - 如何使用 ajax 和 php 制作删除功能
- azure - 从特性创建 PR 到开发分支时,PR 触发器如何工作?构建是否在目标分支触发
- ios - 从字节中获取位的值 | 斯威夫特 5
- intellij-idea - 如何在与 Wildfly 和 IntelliJ 的战争中启用依赖 jar 的资源热交换?
- c++ - 解析字符串 - 无法确定如何分隔连接的单词
- java - 如何使用 lucene 索引创建 RDBMS 橡树存储库
- r - 我无法在 R Shiny 中设置数据表列宽
- vue.js - Workbox 窗口无法安装 Service Worker
- java - 在休息时传输大量数据
- java - 错误:“错误:由于 HttpConnectionTimeout 导致无法获取页面”在 Twitter 卡验证器上