【问题标题】:How to group by period of time?如何按时间段分组?
【发布时间】:2021-11-22 13:44:23
【问题描述】:

我有一个包含消息的表格,我需要在 10 秒内找到两条或更多消息的聊天记录。 表

id message_id time
1  1          13:09:00
1  2          13:09:01
1  3          13:09:50
2  1          15:18:00           
2  2          15:20:00
3  1          15:00:00
3  2          15:10:00
3  3          15:10:10

所以结果看起来像

id
1
3

我想不出如何按时间段进行分组,或者可以用其他方式进行分组?

select id
from t
group by id, ?
having count(message_id) > 1

【问题讨论】:

  • 您可以自行加入。
  • @jarlh 类似于 select t.* from t left join t as t1 on t1.id=t.id and time between time and time + interval 10 sec?

标签: sql postgresql


【解决方案1】:

您可以使用自我join

with add_ymd(id, mid, dt) as (
   select id, message_id, (date(now())||' '||time)::timestamp from messages
),
tm_counts as (
   select t2.id, max(t2.n) + 1 tm from (
     select t.id, t.mid, sum(case when extract(epoch from t.dt - t1.dt) <= 10 then 1 end) n
     from add_ymd t join add_ymd t1 on t.dt > t1.dt group by t.id, t.mid) t2
    where t2.n is not null group by t2.id 
)
select id from tm_counts where tm > 1

输出:

id
---
1
3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-19
    • 2013-06-24
    • 2015-12-19
    • 1970-01-01
    • 2017-10-26
    • 2016-11-25
    • 2011-07-14
    相关资源
    最近更新 更多