多列计数

时间:2015-09-19 14:09:00

标签: mysql sql count sum

我在编写一个查询时遇到问题,该查询总结了2列中所有值的出现次数。我有一个具有以下结构的表:

+-----------+------------+
| player1ID | player2ID  |
+-----------+------------+
| 1         | 2          |
| 1         | 3          |
| 2         | 3          |
| 1         | 4          |
+-----------+------------+

运行查询后,我想要一个像这样的结果表:

+-----------+------------+
| playerID  | count      |
+-----------+------------+
| 1         | 3          |
| 2         | 2          |
| 3         | 2          |
| 4         | 1          |
+-----------+------------+

我尝试了以下查询

select g1.player1ID, g1.count1 + g2.count2 
from 
    (select player1ID, count(*) from table group by player1ID) as g1, 
    (select player2ID, count(*) from table group by player2ID) as g2 
where player1ID = player2ID

但是,如果玩家同时出现在两个列中(player1ID& player2ID),那么它只会给出计数,但如果它只出现在一个或另一个列中,则不会出现。

2 个答案:

答案 0 :(得分:4)

您可以在派生表中使用union,如下所示:

select player, count(*) as count
from (
  select player1id player from table1
  union all
  select player2id player from table1
) sub
group by player;

Sample SQL Fiddle

答案 1 :(得分:0)

使用union all组合两列。然后进行聚合:

select playerID, count(*)
from ((select player1ID as playerID from table) union all
      (select player2ID as playerID from table)
     ) t
group by playerID;