2

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

我想返回一个表格,显示一个玩家(两列玩家)赢得一场游戏的次数(列命名为 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 ) 似乎说查询正常(格式化查询而不是显示错误)。

那么,我做错了什么?

4

2 回答 2

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

于 2013-05-01T11:48:40.433 回答
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;

一个用于测试的 SQLFiddle

于 2013-05-01T11:49:12.673 回答