1

I have a sqlite column with 0 and 1 values and I need to get the max consecutive 1 value. thanks for your help

sqlite> SELECT data_suites  from my_table ;
0
0
1
1
1 <--- 3 consecutive 1
0
1
1
1
1 <--- 4 consecutive 1
0
1
1
1
1
1
1 <---  6 consecutive 1

I am expecting to get

6
joe
  • 103
  • 3
  • 10

1 Answers1

1

Tables are unordered set so you need a column to indicate sorting(id, update_time, ...). Once you have it you could use windowed functions:

WITH cte AS (
 SELECT *,ROW_NUMBER() OVER(ORDER BY id)-ROW_NUMBER() OVER(PARTITION BY data_suites ORDER BY id) grp
 FROM my_table
)
SELECT COUNT(*) cnt
FROM cte
WHERE data_suites = 1
GROUP BY grp
ORDER BY cnt DESC LIMIT 1;
-- answer 6

db<>fiddle demo


WITH cte AS (
  SELECT *, ROW_NUMBER() OVER(ORDER BY id) - ROW_NUMBER() OVER(PARTITION BY data_suites ORDER BY id) grp
  FROM my_table
)
SELECT grp,MIN(id) AS start, MAX(id) AS end, COUNT(*) cnt
FROM cte
WHERE data_suites = 1
GROUP BY grp;

db<>fiddle demo2

Output:

+------+--------+------+-----+
| grp  | start  | end  | cnt |
+------+--------+------+-----+
|   2  |     3  |   5  |   3 |
|   3  |     7  |  10  |   4 |
|   4  |    12  |  17  |   6 |
+------+--------+------+-----+
Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
  • 1
    There is no need for an id column. SQLite provides ROWID. Check your updated demo: https://dbfiddle.uk/?rdbms=sqlite_3.27&fiddle=1cc12d2937cbf587a67129fe2c4fd7dd – forpas Sep 08 '19 at 18:20
  • 1
    @forpas If ROWID is consecutive then yes, there is no need for additional column. – Lukasz Szozda Sep 08 '19 at 18:20
  • 2
    rowids aren't guaranteed to be consecutive even if no rows have been deleted – Shawn Sep 08 '19 at 18:24
  • 2
    Worth pointing out that sqlite window functions require version 3.25 or newer - there's still lots of instances of older versions being used out in the wild. – Shawn Sep 08 '19 at 18:31
  • 1
    @Shawn Yes you are right. It is also pointed out in the link that I've provided: https://stackoverflow.com/questions/16847574/how-to-use-row-number-in-sqlite/51863033#51863033 – Lukasz Szozda Sep 08 '19 at 18:41
  • 1
    Many thanks Lukasz Szozda and all for your help and input, work like a charm – joe Sep 08 '19 at 21:22
  • The code works even if there are gaps between rowids. – forpas Sep 09 '19 at 05:23