SQL query for parent with specific values in child set

无人久伴 提交于 2021-01-28 12:52:39

问题


I am trying to return just the parent where the set of children contain multiple specific records. Given this table:

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

I want find the list of Product that have both a AZ child record and a CA child record, even if it also has other records. Which would return ...

Product
-------
111

回答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'

The last is probably going to be the most efficient.




回答2:


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


来源:https://stackoverflow.com/questions/24332675/sql-query-for-parent-with-specific-values-in-child-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!