我有像这样的MS SQL数据库表
表A
+----+-----------+--------+
|ID | Table2_FK | Value |
+----+-----------+--------+
|1 | 7 | X |
|2 | 7 | Y |
|3 | 8 | X |
|4 | 8 | Z |
|5 | 9 | W |
|6 | 9 | M |
|5 | 10 | X |
|6 | 10 | Z |
+----+-----------+--------+
如果我在查询值时传递X和Z,我想查询获取Table2_FK的列表。在这个例子中,结果是8和10
它可以超过2个值
答案 0 :(得分:1)
您可以使用group by
和having
:
select table2_fk
from t
where value in ('X', 'Z')
group by table2_fk
having count(*) = 2;
如果可以为键值复制值,请使用count(distinct value) = 2
。 “2”是IN
列表中的值的数量。
答案 1 :(得分:0)
试试这个:
select distinct Table2_FK
from TableA
where value in ('X','Z');
答案 2 :(得分:0)
您可以使用以下查询:
Select distinct table2_fk from (
Select *, Ct = count(id) over (partition by table2_fk) from yourtable
) a
Where a.[Value] in ('X','Z') and a.Ct >= 2
答案 3 :(得分:0)
您可以使用下面的查询
select
distinct Table2_FK
from TableA a
where exists (
select 1 1 from TableA b where b.value ='X' and a.Table2_FK =b.Table2_FK
)
and exists (
select 1 1 from TableA c where c.value ='Z' and a.Table2_FK =c.Table2_FK
)