SQL query to count number of times certain values occur in multiple rows

后端 未结 5 1255
慢半拍i
慢半拍i 2021-01-23 09:32

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                


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-23 10:02

    This is as simple as the following

    SELECT voterid, COUNT(DISTINCT electionid) AS electioncount
    FROM table
    WHERE electionid IN (1, 2) /* substitute elections you are interested in here */
    GROUP BY voterid
    HAVING electioncount = 2 /* substiture number of election listed in where condition above
    

    The result set size would provide the number of voters that meet your criteria (i.e. there is no reason to aggregate down furter (i.e. like with subselect) to get to that data.

提交回复
热议问题