Skip to content
Advertisement

Determine if an event happened every hour for 24 straight hours

Edit – I am still digesting the great responses and learning how they work, awesome knowledge!

Using SQL Server 2016, I am trying to figure out if any users have done something at least once every hour, for 24 consecutive hours.

I have a table similar to this, in the example below, the only user who qualifies is ‘21482’. They actually have more than one event an hour (which is fine) but they have done at least one thing every hour for 24 straight hours. They also have events on 8-22 but they would not qualify as they are not consecutive (i.e. there’s a gap between the 8-22 events and 8-23 events).

The other user ‘45578’, does not qualify, even though they have more than 24 events in a single day, there was not activity during every hour for 24 straight hours. It doesn’t matter if the activity spans more than a single day, that is fine.

Ideas on how to accomplish something like this?

Thanks for any suggestions.

Advertisement

Answer

This is a type of gaps-and-islands problem.

There are many solutions.

  • One of the classic ones is to use LAG to check if the current row is the start of a new group, assign group IDs using a running COUNT, then group by this new ID

To truncate to the beginning of the hour, we use DATEADD(hour, DATEDIFF(hour, 0, ad.Event_Timestamp), 0))

  • Another solution is, which works here because all we are looking for is the existence of an island, is to use LAG with an offset of 23 to check whether that row is exactly 23 hours before current. Then we simply group by UserID

db<>fiddle

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement