gpt4 book ai didi

sql - 计算连续天数

转载 作者:行者123 更新时间:2023-12-03 18:41:59 24 4
gpt4 key购买 nike

请我想计算一个事件记录的连续天数,并按此记录分组按 actor id 排序。例如我们有。对于 sqlite

event_id| created_at |actor_id
1 | 2018-07-01| 40 /* this is a consecutive days
1 | 2018-07-02| 40 */
1 | 2018-07-04| 40
1 | 2018-07-05| 40
1 | 2018-07-09| 40
2 | 2018-07-11| 40
2 | 2018-07-12| 40
1 | 2018-07-13| 41

应该给我类似的东西
actor_id|streak
40 | 3
41 | 0

最佳答案

您可以group by actor_id如果存在连续的一天,则有条件地求和:

select 
t.actor_id,
sum(case when exists (
select 1 from tablename
where
actor_id = t.actor_id and
julianday(created_at) - julianday(t.created_at) = 1
) then 1 else 0 end) streak
from tablename t
group by t.actor_id

demo .
或自加入:
select 
t.actor_id,
sum(tt.created_at is not null) streak
from tablename t left join tablename tt
on tt.actor_id = t.actor_id and julianday(tt.created_at) - julianday(t.created_at) = 1
group by t.actor_id

demo .

结果:
| actor_id | streak |
| -------- | ------ |
| 40 | 3 |
| 41 | 0 |

关于sql - 计算连续天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56883969/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com