例如:
pk_ref fk
====== ===
1 a
1 b
1 c
2 a
2 b
2 d
如何执行类似“伪”查询的查询:
select distinc pk_ref
where fk in all('a', 'c');
返回的查询结果必须与列表中外键的所有给定值匹配。
结果应该是:
1
而以下 select 不得返回任何记录。
select distinc pk_ref
where fk in all('a', 'c', 'd');
我怎么做?
尝试这个
select pk_ref
from yourtable
group by pk_ref
having count(case when fk = 'a', then 1 end) >= 1
and count(case when fk = 'c' then 1 end) >= 1
动态地进行。 (考虑到您正在使用 SQL SERVER)
创建分割字符串函数并将输入作为逗号分隔值传递
Declare @input varchar(8000)= 'a,c',@cnt int
set @cnt = len(@input)-len(replace(@input,',','')) + 1
select pk_ref
from yourtable
Where fk in (select split_values from udf_splitstring(@input , ','))
group by pk_ref
having count(Distinct fk) >= @cnt
您可以从以下链接创建分割字符串函数
https://sqlperformance.com/2012/07/t-sql-queries/split-strings https://sqlperformance.com/2012/07/t-sql-queries/split-strings
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)