[英]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... 例如,“对30&68对3票”,“对74&20对1票”,“ 120和116对1票”,依此类推...
I have a SQL query which counts every user mentioned in voted_for but this doesn't include the pair-thing. 我有一个SQL查询,该查询会计算voted_for中提到的每个用户,但这不包括配对事物。 It would give me 4 votes for user 30 but user 30 although is in the 30&121 pair. 它将为用户30给我4票,但用户30虽然在30&121对中。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.