问题
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