Select 每个 ID Table 个不存在的号码
Select non existing Numbers from Table each ID
我是学习 TSQL 的新手,我正在努力获取我的 table 每个 ID 中不存在的数字。
示例:
CustomerID Group
1 1
3 1
6 1
4 2
7 2
我想获取不存在的 ID 并且 select 他们这样
CustomerID Group
2 1
4 1
5 1
5 2
6 2
....
..
使用 cte 的解决方案效果不佳或首先插入数据并执行不存在的 where 子句。
有什么想法吗?
如果您可以接受范围而不是每个范围的列表,那么一种有效的方法是使用 lead()
:
select group_id, (customer_id + 1) as first_missing_customer_id,
(next_ci - 1) as last_missing_customer_id
from (select t.*,
lead(customer_id) over (partition by group_id order by customer_id) as next_ci
from t
) t
where next_ci <> customer_id + 1
交叉连接 2 个递归 CTE 以获得 [CustomerID]
和 [Group]
的所有可能组合,然后 LEFT
连接到 table:
declare @c int = (select max([CustomerID]) from tablename);
declare @g int = (select max([Group]) from tablename);
with
customers as (
select 1 as cust
union all
select cust + 1
from customers where cust < @c
),
groups as (
select 1 as gr
union all
select gr + 1
from groups where gr < @g
),
cte as (
select *
from customers cross join groups
)
select c.cust as [CustomerID], c.gr as [Group]
from cte c left join tablename t
on t.[CustomerID] = c.cust and t.[Group] = c.gr
where t.[CustomerID] is null
and c.cust > (select min([CustomerID]) from tablename where [Group] = c.gr)
and c.cust < (select max([CustomerID]) from tablename where [Group] = c.gr)
参见demo。
结果:
> CustomerID | Group
> ---------: | ----:
> 2 | 1
> 4 | 1
> 5 | 1
> 5 | 2
> 6 | 2
我是学习 TSQL 的新手,我正在努力获取我的 table 每个 ID 中不存在的数字。
示例:
CustomerID Group
1 1
3 1
6 1
4 2
7 2
我想获取不存在的 ID 并且 select 他们这样
CustomerID Group
2 1
4 1
5 1
5 2
6 2
....
..
使用 cte 的解决方案效果不佳或首先插入数据并执行不存在的 where 子句。
有什么想法吗?
如果您可以接受范围而不是每个范围的列表,那么一种有效的方法是使用 lead()
:
select group_id, (customer_id + 1) as first_missing_customer_id,
(next_ci - 1) as last_missing_customer_id
from (select t.*,
lead(customer_id) over (partition by group_id order by customer_id) as next_ci
from t
) t
where next_ci <> customer_id + 1
交叉连接 2 个递归 CTE 以获得 [CustomerID]
和 [Group]
的所有可能组合,然后 LEFT
连接到 table:
declare @c int = (select max([CustomerID]) from tablename);
declare @g int = (select max([Group]) from tablename);
with
customers as (
select 1 as cust
union all
select cust + 1
from customers where cust < @c
),
groups as (
select 1 as gr
union all
select gr + 1
from groups where gr < @g
),
cte as (
select *
from customers cross join groups
)
select c.cust as [CustomerID], c.gr as [Group]
from cte c left join tablename t
on t.[CustomerID] = c.cust and t.[Group] = c.gr
where t.[CustomerID] is null
and c.cust > (select min([CustomerID]) from tablename where [Group] = c.gr)
and c.cust < (select max([CustomerID]) from tablename where [Group] = c.gr)
参见demo。
结果:
> CustomerID | Group
> ---------: | ----:
> 2 | 1
> 4 | 1
> 5 | 1
> 5 | 2
> 6 | 2