我有下表,其中指定了供应商交付产品的区域,其中三列为
ID Supp_ID Area_ID
1 a P
2 a R
3 a T
4 a s
. . .
. . .
5 b R
6 b T
7 b V
. . .
. . .
8 c Z
9 c R
10 c P
11 c T
. . .
. . .
. . .
现在我想要这样一个存储过程,如果我将 Supp_IDs a,b,c 传递给 SP,它应该返回我的 Area_IDs R,T在所有 3 个供应商中共同。简而言之,我必须为给定的 Supp_ID 执行 Area_ID 的交集。
目前我正在尝试的是:
select Area_ID from Table_name where Supp_ID=a
INTERSECT
select Area_ID from Table_name where Supp_ID=b
INTERSECT
select Area_ID from Table_name where Supp_ID=c
当我知道有确切的三个 Supp_ID 时,上面的代码很好 但是当存在不同数量的 Supp_ID 时,我无法找到如何在运行时使用上述逻辑。
现在我找不到我应该如何写在 SP 之上。
提前致谢。
最佳答案
select Area_ID
from Table1
where Supp_ID in ('a', 'b', 'c')
group by Area_ID
having count(distinct Supp_ID) = 3
或者,阐明 3
来自哪里:
declare @Filter table(ID nchar(1) primary key)
insert into @Filter values ('a'), ('b'), ('c')
select a.Area_ID
from Table1 as a
where a.Supp_ID in (select t.ID from @Filter as t)
group by a.Area_ID
having count(distinct Supp_ID) = (select count(*) from @Filter)
关于sql - 根据同一表的第二列的给定值,从表的一列中查找公共(public)值(交集),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19396307/