Skip to content
Advertisement

How do I count events in chronological order in SQL?

I’d like to aggregate Talbe_A and make it like Table_B. It is difficult for me to count events according to the time order. How should I write a Query?

Table_A

Table_B

Advertisement

Answer

This is a gaps-and-islands problem, where you want to group together “adjacent” rows.

Here I think that the simplest approach is to use the difference between row numbers to define the groups:

Demo on DB Fiddle:

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
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement