简体   繁体   中英

SQL - count rows where one column matches another (pairs)

I have a voting system on a website where every user can vote for a pair of users (female and male) to win.

The votes are stored in a table like the one below.

voter_id |  voted_for | cell
90       |  30        | f
90       |  68        | m
42       |  30        | f
42       |  68        | m
111      |  74        | f
111      |  20        | m
45       |  120       | f
16       |  90        | f
16       |  135       | m
122      |  30        | f
122      |  68        | m
45       |  116       | m
46       |  30        | m
46       |  121       | f

Now, I want to count how many users voted for every pair. Eg '3 votes for pair 30&68', '1 vote for pair 74&20', '1 vote for 120&116' and so on...

I have a SQL query which counts every user mentioned in voted_for but this doesn't include the pair-thing. It would give me 4 votes for user 30 but user 30 although is in the 30&121 pair.

SELECT voted_for, count(*) AS count
FROM votes
GROUP BY voted_for
ORDER BY count desc

First transform your table like this:

| voter_id | voted_for_f | voted_for_m |
|----------|-------------|-------------|
|       16 |          90 |         135 |
|       42 |          30 |          68 |
|       45 |         120 |         116 |
|       46 |          30 |         121 |
|       90 |          30 |          68 |
|      111 |          74 |          20 |
|      122 |          30 |          68 |

You can do this with this query, which joins the table with itself:

SELECT f.voter_id,
       f.voted_for AS voted_for_f,
       m.voted_for AS voted_for_m
FROM votes AS f
JOIN votes AS m ON f.voter_id = m.voter_id
               AND f.cell = 'f'
               AND m.cell = 'm'

Then you can use this query to count on it:

SELECT f.voted_for AS voted_for_f,
       m.voted_for AS voted_for_m,
       COUNT(*) AS number_of_votes
FROM votes AS f
JOIN votes AS m ON f.voter_id = m.voter_id
               AND f.cell = 'f'
               AND m.cell = 'm'
GROUP BY voted_for_f,
         voted_for_m

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM