从表中选择不存在的号码每个ID

时间:2019-09-25 12:47:27

标签: sql sql-server tsql range recursive-query

我在学习TSQL方面是新手,我正在努力获取表中每个ID都不存在的数字。

示例:

CustomerID Group
1          1
3          1
6          1       
4          2
7          2

我想获取不存在的ID并选择它们

CustomerID Group
2          1       
4          1
5          1
5          2
6          2
....

..

在cte中使用的解决方案不能很好地工作,或者先插入数据并且不存在where子句。

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

如果您可以使用范围而不是每个列表,那么一种有效的方法是使用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

答案 1 :(得分:0)

交叉联接2个递归CTE,以获得[CustomerID][Group]的所有可能组合,然后LEFT联接到表:

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
相关问题