计算两列并显示符合条件的总数

时间:2013-05-01 11:31:53

标签: mysql

我已经在这里和其他地方看到过这个问题,并且仍然无法得到我想要的结果。所以,请原谅重复。

我想返回一张表格,其中显示了一名玩家(两列玩家)赢了一场比赛的次数(列名为1的地方名单)。

我的查询是:

SELECT `player1` as Winner, Count( * ) AS Count
FROM scores
WHERE `place` =1
UNION ALL
SELECT `player2` as Winner, Count( * ) AS Count
FROM scores
WHERE `place` =1
ORDER  BY count DESC  

表结构是:

player1 varchar
player2 varchar
place   smallint
Other unrelated columns

我想要一个看起来像这样的回复:

Winner     Count
Joe          5
Sam          4
Bill         3

列标签对我来说并不重要,因为我会抓住结果并将其放在网页上。

phpadmin在我的查询中报告错误,而Instant SQLformatter(http://www.dpriver.com/pp/sqlformat.htm?ref=g_wangz)似乎表示查询正常(格式化查询而非显示错误)。

那么,我做错了什么?

2 个答案:

答案 0 :(得分:0)

我会稍微改变查询到以下内容。此查询会将您的player1player2列转换为包含多行的单个列,然后您可以应用计数:

select Winner,
  count(*) Total
from
(
  SELECT `player1` as Winner
  FROM scores
  WHERE `place` =1
  UNION ALL
  SELECT `player2` as Winner
  FROM scores
  WHERE `place` =1
) src
group by winner
order by total desc;

请参阅SQL Fiddle with Demo

答案 1 :(得分:0)

你可以做一个简单的UNION ALL并使用玩家名称上的GROUP BY来计算结果;

SELECT Name AS Winner, COUNT(Name) AS Count
FROM (
  SELECT player1 AS Name FROM Scores WHERE place=1
  UNION ALL
  SELECT player2 AS Name FROM Scores WHERE place=1
) a
GROUP BY Name
ORDER BY Count DESC;

An SQLFiddle to test with