在 PostgreSQL 表中查找序列的间隙

Find gaps of a sequence in PostgreSQL tables

我有 table 个发票字段 invoice_number。这是当我从 invoice

执行 select invoice_number 时发生的情况
invoice_number
1
2
3
5
6
10
11

我想要一个 SQL 给我以下结果:

gap_start gap_end
1 3
5 6
10 11

demo:db<>fiddle

您可以使用 row_number() window function 创建行数并将与实际值的差异用作分组标准:

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