LeB*_*ues 2 sql t-sql sql-server group-by where-clause
Masterid CC CLA DES NLCLA NLDES
-------------------------------------
53006141 CN 0 0 1 1
53006141 US 1 1 1 1
53006141 UK 1 1 0 0
53006142 US 1 1 0 0
53006142 UK 1 1 0 0
53006143 CN 0 0 1 1
53006143 US 1 1 0 0
53006143 UK 1 1 0 0
Run Code Online (Sandbox Code Playgroud)
从上面的数据我需要生产
MasterIds哪里有CC = US或CC = CN和NLCLA = 1和的列表NLDES = 1 输出应该是
53006141
53006143
Run Code Online (Sandbox Code Playgroud)
在MasterID下必须有CN和US.
有人可以帮我在SQL中做这个吗?
您可以通过添加一个WHERE子句来执行此操作,该子句将返回带有US或的行CN:
select distinct Masterid
from yourtable
where cc in ('US', 'CN')
and NLCLA = 1
AND NLDES = 1
Run Code Online (Sandbox Code Playgroud)
如果您希望结果包含CN和US,那么您可以使用:
select Masterid
from yourtable
where cc in ('US', 'CN')
and NLCLA = 1
AND NLDES = 1
group by masterid
having count(distinct cc) = 2
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用a EXISTS来获取带有US和的MasterIds列表CN.然后将其他过滤器放在WHERE子句中而不是子查询中.
select distinct masterid
from yourtable t1
where exists (select Masterid
from yourtable t2
where cc in ('US', 'CN')
and t1.masterid = t2.masterid
group by masterid
having count(distinct cc) = 2)
and NLCLA = 1
and NLDES = 1;
Run Code Online (Sandbox Code Playgroud)