1

如果我的 DATA 样本是

team name  score1  score2
Adele's     15      18
Madonna   16       3
Britanny    9        12

如何使用两列获得前 5 名的分数列表 - 我的输出应该是

Adele's   18
Madonna   16
Adele's   15
Britanny  12
4

3 回答 3

2

Derek Kromm 的答案需要稍作修改,以避免当团队在前 5 名中有两个相同分数时出现错误(例如,与示例相同,除了 Madonna score1 和 score2 均为 16)。union 的默认行为是删除重复的行,因此只保留一个分数。基于这个问题,我认为这不是理想的行为。将“all”关键字添加到 union 将防止此错误。

select * from (
  select team, score1 from tbl
  union all select team, score2 from tbl) a
order by score1 desc
limit 5;

我会将此作为对 Derek Kromm 答案的评论发布,但我没有足够的声誉这样做。抱歉,如果将其作为答案发布不是正确的礼仪。

于 2011-09-10T01:15:21.757 回答
1
SELECT "team name" AS team_name, GREATEST(score1, score2) AS max_score FROM users ORDER BY max_score DESC LIMIT 5

纯粹作为旁注,如果可以的话,值得将数据库中的“团队名称”列重命名为 team_name,因为它使查询和处理数据时变得更加容易:)

于 2011-09-09T23:44:10.380 回答
1

您可以使用 aUNION获取所有团队和分数的列表。然后,使用ORDERLIMIT获得前 5 名。

select * from (
  select team, score1 from tbl
  union select team, score2 from tbl) a
order by score1 desc
limit 5;
于 2011-09-10T00:07:58.070 回答