繁体   English   中英

在顺序的int值中查找缺失的数字SQL Server

[英]Find missing numbers in sequential int values SQL Server

假设我有这张桌子

BookNo. | page
001     |  01
001     |  02
001     |  04
002     |  01
002     |  03
003     |  01
003     |  02

是否可以获取缺少页码的书号?

这将起作用,除非缺少第1页(在oracle上编写,因此语法可能略有不同):

with cte1 as (
select distinct
   BookNo
  ,case when a.page + 1 != lead(page) over (partition by bookno order by page) then page + 1 end as missing_start
  ,case when a.page + 1 != lead(page) over (partition by bookno order by page) then lead(page) over (partition by bookno order by page) - 1 end as missing_end
from test a
where 1=1
)
select *
from cte1
where missing_start is not null
order by 1
;

结果:

| BOOKNO | MISSING_START | MISSING_END |
|--------|---------------|-------------|
| 001    | 3             | 3           |
| 002    | 2             | 2           |

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM