连续计数

时间:2019-07-04 08:46:28

标签: sql sqlite

请按事件记录和演员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

1 个答案:

答案 0 :(得分:2)

如果连续存在一天,您可以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      |