如何按时间顺序计算 SQL 中的事件?
How do I count events in chronological order in SQL?
我想聚合 Talbe_A 并使它像 Table_B。
我很难按照时间顺序来统计事件。
我应该如何编写查询?
Table_A
client_id event time
A view 12:00:00
A view 12:02:00
A view 12:05:00
A purchase 14:02:00
B view 12:04:00
B view 12:07:00
B view 13:20:00
C view 12:00:00
C view 12:07:00
C add_to_cart 14:02:00
C view 14:19:00
C purchase 14:32:00
C view 15:32:00
Table_B
client_id event count
A view 3
A purchase 1
B view 3
C view 3
C add_to_cart 1
C view 1
C purchase 1
C view 1
这是一个 gaps-and-islands 问题,您希望将“相邻”行组合在一起。
这里我认为最简单的做法是使用行号的不同来定义分组:
select client_id, event, count(*) cnt, min(time) start_time, max(time) end_time
from (
select
t.*,
row_number() over(partition by client_id order by time) rn1,
row_number() over(partition by client_id, event order by time) rn2
from mytable t
) t
group by client_id, event, rn1 - rn2
order by client_id, min(time)
client_id | event | cnt | start_time | end_time
:-------- | :---------- | --: | :--------- | :-------
A | view | 3 | 12:00:00 | 12:05:00
A | purchase | 1 | 14:02:00 | 14:02:00
B | view | 3 | 12:04:00 | 13:20:00
C | view | 2 | 12:00:00 | 12:07:00
C | add_to_cart | 1 | 14:02:00 | 14:02:00
C | view | 1 | 14:19:00 | 14:19:00
C | purchase | 1 | 14:32:00 | 14:32:00
C | view | 1 | 15:32:00 | 15:32:00
我想聚合 Talbe_A 并使它像 Table_B。 我很难按照时间顺序来统计事件。 我应该如何编写查询?
Table_A
client_id event time
A view 12:00:00
A view 12:02:00
A view 12:05:00
A purchase 14:02:00
B view 12:04:00
B view 12:07:00
B view 13:20:00
C view 12:00:00
C view 12:07:00
C add_to_cart 14:02:00
C view 14:19:00
C purchase 14:32:00
C view 15:32:00
Table_B
client_id event count
A view 3
A purchase 1
B view 3
C view 3
C add_to_cart 1
C view 1
C purchase 1
C view 1
这是一个 gaps-and-islands 问题,您希望将“相邻”行组合在一起。
这里我认为最简单的做法是使用行号的不同来定义分组:
select client_id, event, count(*) cnt, min(time) start_time, max(time) end_time
from (
select
t.*,
row_number() over(partition by client_id order by time) rn1,
row_number() over(partition by client_id, event order by time) rn2
from mytable t
) t
group by client_id, event, rn1 - rn2
order by client_id, min(time)
client_id | event | cnt | start_time | end_time :-------- | :---------- | --: | :--------- | :------- A | view | 3 | 12:00:00 | 12:05:00 A | purchase | 1 | 14:02:00 | 14:02:00 B | view | 3 | 12:04:00 | 13:20:00 C | view | 2 | 12:00:00 | 12:07:00 C | add_to_cart | 1 | 14:02:00 | 14:02:00 C | view | 1 | 14:19:00 | 14:19:00 C | purchase | 1 | 14:32:00 | 14:32:00 C | view | 1 | 15:32:00 | 15:32:00