按分组选择两列的计数

时间:2015-02-07 12:48:47

标签: mysql sql

我试图在下表中为表中存在的每个玩家名称选择玩家赢了和输的次数。

此表记录了比赛。

┌──┬────────┬────────┐
│id│winner  │loser   │
├──┼────────┼────────┤
│1 │player1 │ player2│
├──┼────────┼────────┤
│2 │player1 │ player2│
├──┼────────┼────────┤
│3 │player2 │ player1│
├──┼────────┼────────┤
│4 │player3 │ player2│
└──┴────────┴────────┘

示例:在上表中,player1将有两次胜利和一次失败。我试图选择每个玩家的胜负数量。

我目前有以下SQL

SELECT winner, count(winner) FROM multiplayergamestbl GROUP BY winner

这将使每位玩家获得胜利,但是损失的数量不是我所期望的,损失的数量将返回与获胜次数相同的值。我显然对SQL有点新鲜,有人可以帮助我吗?

3 个答案:

答案 0 :(得分:1)

执行此操作的一种方法是执行两个单独的查询(一个用于获胜者计数,一个用于失败者计数)并将它们组合在一起并将结果用作派生表,如下所示:

select player, max(count_winner), max(count_loser) 
from (

  SELECT winner as player, count(winner) as count_winner, null as count_loser 
  FROM multiplayergamestbl 
  GROUP BY winner

  union all

  SELECT loser as player, null as count_winner, count(loser) as count_loser
  FROM multiplayergamestbl 
  GROUP BY loser

  ) t
group by player;

外部查询使用最大聚合函数来展平行,如果没有它,您将获得五行而不是三行(请参阅this example)。

Sample SQL Fiddle

答案 1 :(得分:1)

首先把你的表变成更像是使用子查询的格式,然后对它做一个简单的总结:

select player, sum(won) won, sum(lost) lost from (
  select winner player, 1 won, 0 lost from multiplayergamestbl
  union select loser, 0, 1 from multiplayergamestbl) x
group by player

答案 2 :(得分:0)

这可能与你想要的一样。

select 'winner' category
, winner
, count(*) records
from multiplayergamestbl 
group by 'winner', winner

union

select 'loser' category
, loser
, count(*) records
from multiplayergamestbl