简体   繁体   中英

SQLite - Finding consecutive days

I am trying to get the current amount of consecutive days for a challenge known as the current streak. Additionally I want to find the most consecutive days known as longest streak. I saved the dates in my database using the format "yyyy/MM/dd".

If I'm just searching for all of the dates and the associated challengeid I have this code:

SELECT CHALLENGEID, DATE FROM ACTIVE_CHALLENGES_TABLE ORDER BY CHALLENGEID, DATE

The result is:

| CHALLENGEID | DATE          |
|-----------------------------|
| 1           | 14/10/2020    |
| 1           | 15/10/2020    |
| 1           | 16/10/2020    |
| 1           | 24/10/2020    |
| 1           | 27/10/2020    |
| 2           | 14/10/2020    |
| 2           | 15/10/2020    |
| 2           | 19/10/2020    |
| 3           | 13/10/2020    |
| 3           | 15/10/2020    |
| ...         | ...

So I have the columns challengeid and date. Can you please help me as I'm not knowing how to get data like current streak (from the current day backwards) and the longest streak?

The result should look like this:

| CHALLENGEID | MAX_STREAK    | CURRENT_STREAK |
|----------------------------------------------|
| 1           | 3             | 1              | //assume today is 27/10/2020
| 2           | 2             | 0              |
| 3           | 1             | 0              |
|...

Thank you!

This is a type of gaps-and-islands problem. You can generate a sequence of numbers and the difference between that and the date is constant for a "streak". The rest is just aggregation:

select challenge_id, max(length) as max_streak,
       max(case when max(date) = date('now') then streak else 0 end) as current_streak
from (select challenge_id, min(date) as min_date, max(date) as max_date, count(*) as length            
      from (select t.*,
                   row_number() over (partition by challengeid order by date) as seqnum
            from ACTIVE_CHALLENGES_TABLE  t
           ) t
      group by challengeid, date(date, '-' || seqnum || ' day')
     ) c
group by challenge_id;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM