使用COUNT并将两列的值相加

时间:2015-01-25 21:56:02

标签: mysql sql select count

我有这张表,其中包含投票的价值:

+-------+-------+
| Vote1 | Vote2 |
+-------+-------+
| Mr. X | Mr. Y |
| Mr. X | Mr. Z |
| Mr. Y | Mr. X |
| Mr. Z | Mr. X |
+-------+-------+

现在我需要表中提到的每个人的总发生次数,如下所示:

+--------+-------+
| Person | Votes |
+--------+-------+
| Mr. X  |     4 |
| Mr. Y  |     2 |
| Mr. Z  |     2 |
+--------+-------+

现在我必须通过对两列中的每一列进行COUNT查询来手动计算总和。

2 个答案:

答案 0 :(得分:2)

您可以使用union all运算符来序列化两列:

SELECT   person, COUNT(*) AS votes
FROM     (SELECT vote1 AS person
          FROM   mytable
          UNION ALL
          SELECT vote2 AS person
          FROM   mytable) t
GROUP BY person

答案 1 :(得分:2)

要获得更高的性能,请使用此查询:

SELECT Vote1 Person, (Count(Vote1) + Count(Vote2))Votes FROM mytable GROUP BY Vote1

SELECT Vote2 Person, (Count(Vote1) + Count(Vote2))Votes FROM mytable GROUP BY Vote2

尽可能避免使用UNION or UNION ALL