I want to select distinct values of a column, with the additional clause that the multiple rows for that value should satisfy all criteria (amongst them).
For example, in the below table I want to say: "Distinct Name
where key=1 AND value=2
AND key=2 AND value=2
".
This should return "valid" only. "invalid1" fails because although it satisfies the first criteria, no other row satisfies the other criteria. "invalid2" fails because it satisfies neither criteria.
id Name Key Value
====== ========= ==== ===========
1 valid 1 2
2 valid 2 2
3 invalid1 1 2
4 invalid2 1 3
Use group by
with having
. The conditions in having
are treated as booleans and return 1 for true and 0 for false.
select name
from t
group by name
having sum(key=1 and value=2)=1 and sum(key=2 and value=2)=1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.