SQL - 计算一列与另一列匹配的行(对)

时间:2015-04-20 13:02:08

标签: sql sqlite join count

我在一个网站上有一个投票系统,每个用户都可以投票给一对用户(女性和男性)赢得胜利。

投票存储在如下表格中。

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

现在,我想计算每对投票的用户数量。 例如。 ' 3票对30& 68',' 1投票对74& 20'' 1投票给120& 116'等等...

我有一个SQL查询,它统计了voted_for中提到的每个用户,但是这并不包括这对东西。对于用户30,它将给我4票,但是用户30虽然在30& 121对中。

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

1 个答案:

答案 0 :(得分:1)

首先像这样转换你的表:

| 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 |

您可以使用此查询来执行此操作,该查询将表连接到自身:

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'

然后您可以使用此查询来指望它:

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