Counting events only once if an event happens more than once every X minutes

I have a table that is filled everytime a user starts a session in my app. But I dont want to count their session more than once if they make it within 10 minutes. How can I do it?

Here's an example of what is returned from the table

   select
    *
    from table
    limit 100


+----------+--------+---------+----------------+
| event_ID | userid | city_id |   created_at   |
+----------+--------+---------+----------------+
|        1 | a      |       1 | 15/08/19 10:10 |
|        2 | b      |       1 | 15/08/19 10:11 |
|        3 | a      |       1 | 15/08/19 10:14 |
|        4 | a      |       1 | 15/08/19 10:25 |
|        5 | b      |       1 | 15/08/19 10:27 |
|        6 | c      |       1 | 15/08/19 10:30 |
|        7 | c      |       1 | 15/08/19 10:35 |
|        8 | d      |       1 | 15/08/19 10:40 |
|        9 | d      |       1 | 15/08/19 10:49 |
|       10 | c      |       1 | 15/08/19 10:55 |
+----------+--------+---------+----------------+

In the end, I would want to count the unique event_ids for each user, based on the premise that a unique event_id is defined by the amount of times it happens every 10 minutes

So it should be something like this in the end:

+--------+------------------+
| userid | unique_event_ids |
+--------+------------------+
| a      |                2 |
| b      |                2 |
| c      |                2 |
| d      |                1 |
+--------+------------------+
+--------+------------------+
| Total  |                7 |
+--------+------------------+

Any suggestion on how to start?

Upvotes: 2

Views: 144

Answers (2)

The Impaler
The Impaler

Reputation: 48865

I would do:

select
  userid,
  sum(case when created_at - interval '10 minute' < prev then 0 else 1 end)
    as unique_events_ids
from (
  select
    *,
    lag(created_at) over(partition by userid order by created_at) as prev
  from t
) x
group by userid

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1270993

Use lag() to determine when the previous event was created for the user. Then some date filtering and aggregation:

select userid, count(*)
from (select t.*,
             lag(created_at) over (partition by userid order by created_at) as prev_created_at
      from t
     ) t
where prev_created_at is null or prev_created_at < created_at - interval '10 minute'
group by userid

Upvotes: 1

Related Questions