
As you can see, this solution has to hardcode the value of 2 in the query to answer for 3 consecutive days. (SELECT COUNT(*) FROM sum_flags sf2 WHERE sf2.grp = sf1.grp AND sf2.time <= sf1. If we count 3, that means there is a streak of 3. (SELECT COUNT(*) FROM sum_flags sf2 WHERE sf2.grp = sf1.grp) count, SELECT t1.*, t1.type COALESCE(t2.type, '') flag, MAX(t2.time) max_timeįROM prev_types pt1 INNER JOIN prev_types pt2 WHERE numConsecutiveItems IS NULL OR rn = 1įor versions of SQLite that do not support window functions, use aggregations and correlated subqueries to simulate the window functions: WITH SELECT *, (type LAG(type, 1, '') OVER (ORDER BY time)) flagĬASE WHEN type = 'new_item' THEN count END numConsecutiveItems select gamepk ,gameds ,awayteam ,hometeam ,homeaway ,rownumber () over (partition by grp order by gameds) as hacnt from ( select ,count (chng) over (order by gameds) as grp from ( select. SELECT *, SUM(flag) OVER (ORDER BY time) grp We mark every change, use count () over () to make groups out of each consecutive run and then use rownumber () to number them by date. ROW_NUMBER() OVER (PARTITION BY grp ORDER BY time) rn Use window functions to create the groups of consecutive types and count how many of them are 'new_item' in each group: WITH cte AS ( Can I achieve this with a single query, and ordered by the time column? That will be my strong preference, but if not then ideally no more than 2 queries.

More so, the message with id of fifth is present because it doesn't immediately follow another new_item message, and its value of numConsecutiveItems is 1 for the same reason. Notice that the message with id of third is not in the final output because it has type of new_item and consecutively follows another message with type new_item, and the message with id of second has numConsecutiveItems of 2 for the same reason. Concretely, I would like output that gives me the information captured below (doesn't have to be the same schema, this is just an example of what I want): [ I want to query these messages such that consecutive rows with type of new_item are represented as one, as well as the number of consecutive rows that are present for each unique new_item in the final output. Imagine that I have 5 rows in the following order (representing them as a JSON array for clarity): [ The fallbacks cause the device to stall and then crash when the table being queried contains hundreds of rows, so I can't rely on those.Ĭonsider that I have a sqlite table called messages with these columns: | id | type | text | time |

#Sqlite count consecutive android
I need this to work on sqlite going back to at least version 3.19.4 (effectively Android 8), and the most performant form of the accepted answer (using window functions) is not available before version 3.28 of sqlite. I'm still open to other suggestions even though there's an accepted answer.
