我有一个名为Supplier的表。
ID SupplierGroup
101 FAC_A
101 FAC_B
101 FAC_C
101 FAC_D
202 FAC_A
202 FAC_B
202 FAC_D
303 FAC_B
303 FAC_C
303 FAC_D
404 FAC_A
404 FAC_B
404 FAC_C
404 FAC_D
505 FAC_C
505 FAC_D
我必须获得供应商的不同ID,而不是FAC_A作为SupplierGroup。我用过这个查询..
select distinct ID
from Supplier
where SupplierGroup not in ('FAC_A')
但我的查询有问题。它导致了
ID
101
202
303
404
505
它应该得到
的结果ID
303
505
答案 0 :(得分:2)
一种解决方案是使用NOT EXISTS:
select distinct s.ID
from Supplier s
where
not exists (select * from Supplier
where supplier.ID=s.ID and
supplier.SupplierGroup ='FAC_A')
另一个解决方案是使用GROUP BY并计算FAC_A值:
select ID
from Supplier
group by ID
having
sum(case when SupplierGroup ='FAC_A' then 1 else 0 end)=0
答案 1 :(得分:1)
使用OUTER APPLY的另一种方法:
SELECT DISTINCT s.ID
FROM Supplier s
OUTER APPLY (SELECT TOP 1 * FROM Supplier WHERE SupplierGroup IN ('FAC_A') AND ID = s.ID) p
WHERE p.ID IS NULL
输出:
ID
303
505