Reputation: 182
I am struggling with listing the gaps including their lower and upper bounds in a simple SQLite table.
The table:
id
1
2
5
6
8
What I want is a result like (cnt is counting the missing integers):
lb ub cnt
2 5 2
6 8 1
I have already found the gaps, but no idea how to put lower and upper bounds together and count the missing integers:
SELECT id FROM table mo WHERE NOT EXISTS ( SELECT NULL FROM messages mi WHERE mi._id = mo._id + 1 ) ORDER BY id
Replacing the condition with -1 I get the other bounds.
Upvotes: 1
Views: 157
Reputation: 52549
Looks like a straightforward gaps and islands problem.
CREATE TABLE test(id INTEGER PRIMARY KEY);
INSERT INTO test VALUES (1), (2), (5), (6), (8);
WITH ranges AS (SELECT id AS lb, lead(id, 1) OVER (ORDER BY id) AS ub FROM test)
SELECT lb, ub, ub - lb - 1 AS cnt FROM ranges WHERE ub - lb > 1;
gives
lb ub cnt
---------- ---------- ----------
2 5 2
6 8 1
(Note: The above requires Sqlite 3.25 or newer)
Upvotes: 1