1

I have a table invoices with a field invoice_number. This is what happens when i execute select invoice_number from invoice

invoice_number
1
2
3
5
6
10
11

I want a SQL that gives me the following result:

gap_start gap_end
1 3
5 6
10 11
2

1 Answer 1

6

demo:db<>fiddle

You can use row_number() window function to create a row count and use the difference to your actual values as group criterion:

SELECT
    MIN(invoice) AS start,
    MAX(invoice) AS end
FROM (
    SELECT
        *,
        invoice - row_number() OVER (ORDER BY invoice) as group_id
    FROM t
) s
GROUP BY group_id
ORDER BY start
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.