Let’s assume we have a table Maintenance
Customer LastLogin ActionType
1 12/1/2007 2
1 12/2/2007 2
etc.
We want a list of all customers who at any point during a given year had one or more uninterrupted sequences, 14 days long, of login with action type 2.
I can of course easily do this with code, and even have it be fairly quick over small sets. Is there a non-cursor way to do it in SQL?
This will select all customers with at least two consecutive actions of the same type.
Here’s the more efficient query for just action
2:Update 2:
To select uninterrupted ranges:
This query calculates two series: one returns contiguous
ORDER BY lastlogin, the second one partitions byactionadditionally:As long as the difference between the two schemes is the same, the series are uninterrupted. Each interruption breaks the series.
This means that the combination of (
action, diff) defines the uninterrupted groups.We can group by
action, diff, findMAXandMINwithin the groups and filter on them.If you need to select
14rows rather than14consecutive days, just filter onCOUNT(*)instead of theDATEDIFF.