Skip to content
Advertisement

Finding date-streak in SQL

I got my sqlite table with entries having a DateTime field. I want to check if there are entries with n consecutive days. Like a streak. Now I could just query all entries ordered by the date-field and iterate over them and check by myself. I am just wondering if there is some more efficient way to do this. Like a build-in function in SQL that I don’t know about or something like that.

Thanks for your advice!

example data:

Looking for a 5-day-streak, this should result true. Because of date 3-7.

Advertisement

Answer

Assuming the data has no duplicates, you can use lag(). So, if you wanted to see if 5 dates were in a row:

Basically, this “goes back” four rows and peaks at the date. If that days is exactly 4 days before, then there are five days in sequence.

EDIT:

If you have duplicates, remove them in a subquery:

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