在SQL中查找序列的间隙而不创建其他表

时间:2015-05-11 13:03:16

标签: sql postgresql gaps-and-islands

我有一个表invoices,其中包含字段invoice_number。这是我执行select invoice_number from invoice时发生的事情:

invoice_number
--------------
1
2
3
5
6
10
11

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

gap_start | gap_end
4         | 4
7         | 9

如何编写SQL来执行此类查询? 我正在使用PostgreSQL。

2 个答案:

答案 0 :(得分:17)

使用modern SQL,可以使用window functions轻松完成:

select invoice_number + 1 as gap_start, 
       next_nr - 1 as gap_end
from (
  select invoice_number, 
         lead(invoice_number) over (order by invoice_number) as next_nr
  from invoices
) nr
where invoice_number + 1 <> next_nr;

SQLFiddle:http://sqlfiddle.com/#!15/1e807/1

答案 1 :(得分:1)

我发现了另一个问题:

 select invoice_number + lag gap_start, 
        invoice_number + lead - 1 gap_end
    from (select invoice_number, 
                 invoice_number - lag(invoice_number) over w lag,
                 lead(invoice_number) over w - invoice_number lead 
              from invoices window w as (order by invoice_number)) x 
  where lag = 1 and lead > 1;