sql - 使用 SQL Server 查找列中的空白
问题描述
我有一个带有 int 类型列的表,它不是主键。我有一千条记录。
我想找到丢失的身份证。
我有这些数据:
1
2
3
4
6
8
11
14
我想要这个结果:5,7,9,10,12,13
你知道我该怎么做吗?
谢谢,
解决方案
将其作为范围更容易:
select (col + 1) as first_missing, (next_col - 1) as last_missing
from (select t.*, lead(col) over (order by col) as next_col
from t
) t
where next_col <> col + 1;
如果您确实希望将此作为列表,我建议使用递归 CTE:
with cte as (
select t.col, lead(col) over (order by col) as next_col, 1 as lev
from t
union all
select cte.col + 1, next_col, lev + 1
from cte
where col + 1 < next_col
)
select cte.col
from cte
where lev > 1;
注意:如果间隙可以超过 100,则需要OPTION (MAXRECURSION 0)
.
这是一个 db<>fiddle。
推荐阅读
- python - 如何在 python 中更快地计算多个点组合之间的最小地理距离?
- javascript - 如何在 Ionic React 中通过 onChange 调用传递切换状态?
- ubuntu - jupyter notebook 打不开:拒绝访问
- swift - collectionView 不 scrollToItem - swift - 以编程方式
- angular - 在 scrollDispatcher Angular Material 上滚动的方法总是返回 undefined
- r - 试图协调 R Shiny 反应值中的日志记录和 textOutput
- android - 工具栏正在覆盖 Recyclerview
- r - 在R中重复向量化矩阵的最佳方法?
- javascript - 获取异步变量返回空
- java - Java WebLookAndFeel 不显示 JXTable 的列控制弹出菜单