COUNT the # of DISTINCT IDs, but only when multiple records exist in a table
Let's say I have开发者_StackOverflow中文版 the following MySQL table:
id tagid campaignid 1 10 1000 2 11 1000 3 12 1000 4 13 1000 5 12 2000 6 13 2000 7 12 3000 7 12 4000
I need to COUNT the number of DISTINCT campaignids, but only when records exist for multiple tagids.
For example, count the number of unique campaignids when a record exists for all of the following tagids - 10, 11 & 12. In this case, the result would be a count of 1 (only campaignid 1000 has a record for all of these tagids)
Another example, count the number of unique campaignid when a record exists for both tagid 12 & 13. In this case, the result would be a count of 2 (campaignid 1000 & 2000 both have a record for both of these tagids). campaignid 3000 & 4000 have a record for tagid 12, but not a record for tagid 13, so they are not included.
Any thoughts on the SQL statement I could use to accomplish this?
Many thanks.
A somewhat simplified version of Jack Maney's answer using Having
SELECT Count(campaignid)
FROM
(SELECT campaignid
FROM table
HAVING count(tagid) > 1
GROUP BY campaignid ) t
Assuming you're interested in the occurrence of a specific list of tagIDs perhaps something like the following: (Disclaimer: I use Sql Server)
select count(campaignid)
from (
select campaignid
from table
where tagid in (12, 13) --change the list of tagids as desired
group by campaignid
having count(distinct tagid)=2 --this count should be the exact size of the tagid list above
) t
Just count the campaignid's for each (id,tagid) pair, only take the rows where this count is at least 2, and then do a final tally:
select count(1) from
(
select campaignid from
(
select id, tagid, count(campaignid) as freq
from table
group by id, tagid
)
join table using (id,tagid)
where freq>=2
group by campaignid
)
精彩评论