SQL为每个PlayerID获取行的SUM

时间:2013-01-04 20:04:09

标签: mysql sql sum

我的布局看起来像这样:

Player:
PlayerID - PlayerName

Exp
ExpID - PlayerID - ExpChange

我要做的是获取每个玩家名称的ExpChange之和,并按照expchange的总和进行排序。 (以SUM(ExpChange)为分数的高分列表。

这是我到目前为止所做的:

SELECT Player.PlayerName, Exp.ExpChange
FROM Player
INNER JOIN Exp
ON Player.PlayerID=Exp.PlayerID
ORDER BY Exp.ExpChange;

但是现在我需要以某种方式按照该玩家的expchange总和对每个玩家进行排序。这可能吗?我试着寻找它,但找不到任何东西。感谢

P.S。我也试过这样的事情:

SELECT Player.PlayerName, SUM(Exp.ExpChange) AS exp
FROM Player
INNER JOIN Exp
ON Player.PlayerID=Exp.PlayerID
ORDER BY exp;

但它只输出每个人的总ExpChange,而不是每个玩家。

2 个答案:

答案 0 :(得分:11)

您需要添加GROUP BY子句以获取每个sum()的{​​{1}}:

player

如果您只想要SELECT Player.PlayerName, SUM(COALESCE(Exp.ExpChange, 0)) AS exp FROM Player LEFT JOIN Exp ON Player.PlayerID=Exp.PlayerID GROUP BY Player.PlayerName ORDER BY exp; 表中匹配的记录,那么您可以使用exp

INNER JOIN

答案 1 :(得分:0)

试试这个

  SELECT P.PlayerName, SUM(Exp.ExpChange) AS exp
  FROM Player p
  INNER JOIN Exp
  ON p.PlayerID=Exp.PlayerID
  GROUP BY p.PlayerName
  ORDER BY exp;