P粉5118967162023-08-24 17:05:54
use:
SELECT t.contactid FROM YOUR_TABLE t WHERE flag IN ('Volunteer', 'Uploaded') GROUP BY t.contactid HAVING COUNT(DISTINCT t.flag) = 2
The key is that the count of t.flag
needs to be equal to the number of parameters in the IN
clause.
The use of COUNT(DISTINCT t.flag)
is to prevent the combination of contactid and flag from not having a unique constraint - if there is no chance of duplication, you can omit the DISTINCT from the query:
SELECT t.contactid FROM YOUR_TABLE t WHERE flag IN ('Volunteer', 'Uploaded') GROUP BY t.contactid HAVING COUNT(t.flag) = 2
P粉1388714852023-08-24 11:10:07
You can use GROUP BY
and HAVING COUNT(*) = _
:
SELECT contact_id FROM your_table WHERE flag IN ('Volunteer', 'Uploaded', ...) GROUP BY contact_id HAVING COUNT(*) = 2 -- // must match number in the WHERE flag IN (...) list
(assuming contact_id, flag
are unique).
Or use connection:
SELECT T1.contact_id FROM your_table T1 JOIN your_table T2 ON T1.contact_id = T2.contact_id AND T2.flag = 'Uploaded' -- // more joins if necessary WHERE T1.flag = 'Volunteer'
If the flag list is long and there are many matches, the first one may be faster. If the flag list is short and there are few matches, you may find the second one to be faster. If performance is an issue, try testing it on your data to see which one works best.