检查每个组的另一列中是否存在列值

问题描述 投票:0回答:2

我有三个变量:组变量var1和var2。每组,var2中的每个值都应存在于var1中。我想返回不是这种情况的所有组(因此,当var2未包含在var1中时,我希望知道每组)

例:

mygroup  var1       var2
1          1          -
1          2          1
1          3          2
1          4          -
2         23         23 
2         24         20 
2         26          -
3         30         10
3         20          -
3         10          -

所以在这种情况下,我希望我的输出为组2,因为20不包含在var1中(在组2中)。

任何帮助将不胜感激。

sql group-by exists
2个回答
2
投票

使用不存在

select mygroup from table_name t1
where not exists( select 1 from table_name t2 where t1.var2=t2.var1
                and t1.mygroup=t2.mygroup)
       and t1.var2 is not null 

1
投票

另一种使用cte和temp表的方法:

  1. 找出同一mygroup的var1中未包含的var2值
  2. 列出mygroups并将它们分组到您在步骤1中找到的列表中的var2。

试试以下:

create table #temp (mygroup int, var1 int, var2 int)
insert into #temp values 
(1 ,         1,          null),
(1 ,         2,         1),
(1 ,         3,          2),
(1 ,         4,          null),
(2 ,        23,         23 ),
(2 ,        24,         20 ),
(2 ,        26,          null),
(3 ,        30,         10),
(3 ,        20,          null),
(3 ,        10,          null)

;with cte as (
select t.mygroup, t.var1, t2.var2
from #temp t
inner join #temp t2 on t2.var2=t.var1 and t2.mygroup = t.mygroup
)
select var2
into #notIncludeList
from #temp 
where var2 not in (select var1 from cte)

select mygroup
from #temp
where var2 in (select var2 from #notIncludeList)
group by mygroup

该解决方案适用于MsSql-2014。

© www.soinside.com 2019 - 2024. All rights reserved.