Skip to content
Advertisement

Return number of rows (streak count) from entries where each entry is the previous days date

I have a table with two columns, userid and date. I want to query this table using a specific userid and date, and from that I want to return the row count of entries going backwards from the entered date. i.e. where userid = 1 AND date = '2020-07-09'. It should stop counting if there is a gap between the next date.

So here’s my table:

The streak for userid 1 and date 2020-07-29 would be 3.

Now if I remove an entry:

The streak for userid 1 and date 2020-07-29 would be 1. This is because the 2020-07-28 date is missing for the userid.

How could I do this with postgres sql? I have looked into the generate_series function but this requires me to set a start and end date.

Advertisement

Answer

You could achieve this using the following:

Approach 1

Using window functions, you could achieve this eg

or replace MAX("date") - MIN("date") + 1 with COUNT(1), or if you would like the entire row data

or replace MAX("date") OVER (PARTITION BY gn,"userid") - MIN("date") OVER (PARTITION BY gn,"userid") + 1 with COUNT(1) OVER (PARTITION BY gn,"userid").

NB. Since we have filtered based on userid we could simple partition by gn only

Approach 2

Create a function to extract the streak. This function loops through the data and breaks when it determines that the streak has been broken.

with example usage

Approach 3

This approach identifies the streak using the difference from the chosen date and row number

Demo

You may view a working demo with test cases here

Let me know if this works for you.

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