Find gaps of a sequence in SQL without creating additional tables

老子叫甜甜 提交于 2021-02-18 11:29:14

问题


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
4         | 4
7         | 9

How can i write a SQL to perform such query? I am using PostgreSQL.


回答1:


With modern SQL, this can easily be done using 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




回答2:


I found another query:

 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;


来源:https://stackoverflow.com/questions/30168418/find-gaps-of-a-sequence-in-sql-without-creating-additional-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!