父查询在子集中具有特定值的SQL查询

时间:2014-06-20 17:30:13

标签: sql sql-server tsql set-theory

我试图只返回子集包含多个特定记录的父节点。鉴于此表:

Product   State
-------   -----
111       AZ
111       CA
111       UT
222       AZ
222       WA
333       CA

我想查找同时包含Product子记录和AZ子记录的CA列表,即使它还有其他记录。哪会回来......

Product
-------
111

2 个答案:

答案 0 :(得分:1)

SELECT product 
FROM table 
GROUP BY product 
HAVING SUM(CASE WHEN State 'AZ' THEN 1 ELSE 0 END) > 1
   AND SUM(CASE WHEN State 'CA' THEN 1 ELSE 0 END) > 1

答案 1 :(得分:1)

select product  
  from table 
 where state in ('az','ca')  
 group by product 
having count(distinct(state)) = 2


select distinct product  
  from table 
 where state = 'az'
INTERSECT 
select distinct product  
  from table 
 where state = 'ca'  


select distinct t1.product  
  from table t1 
  join table t2 
    on t1.product = t2.product 
   and t1.state = 'az'
   and t2.state = 'ca'

最后一个可能是效率最高的。