Suppose I have a table of election data, call it ELECTIONS, with one row per voter per election, like so:
VoterID ElectionID
A 1
A 2
B 1
C 2
D 3
E 1
E 2
I want to know the number of voters who voted both in election 1 and in election 2; I don't care about anyone else. The number should be 2 (voter A and Voter E).
Would something like this work:
select count(Elections) as NumVoters
from (
select VoterID, ElectionID, count(ElectionID) as Elections
from ELECTIONS
where ElectionID=1 or ElectionID=2
group by VoterID
having (count(ElectionID)=2)
) x;
UPDATE: This is my first question here, and I am blown away at how helpful and fast folks have been. I revised the query above to fix the lack of an alias at the end and to add a terminating semicolon.
THANK YOU!