如何在SUM生成的列上找到MAX值

时间:2017-07-31 17:57:23

标签: mysql sql database

这是我的数据

+---------+-------------+
| playerName | score    |
+---------+-------------+
| Player1    | 1        |
| Player2    | 1        |
| Player3    | 1        |
| Player1    | 0        |
| Player2    | 1        |
| Player3    | 1        |
| Player1    | 1        |
| Player2    | 0        |
| Player3    | 1        |
| Player3    | 1        |
+---------+-------------+

但是当我使用这个查询时:

SELECT tt.playerName, MAX(sumS) AS max2 FROM table1 tt INNER JOIN (SELECT playerName,Sum(score) AS sumS FROM table1 GROUP BY playerName) T2 ON tt.playerName= t2.playerName

我得到了:

+---------+-------------+
|playerName| score      |
+---------+-------------+
| Player1  | 4          |
+---------+-------------+
  

但我正在寻找这个结果:

+---------+-------------+
|playerName| score      |
+---------+-------------+
| Player3  | 4          |
+---------+-------------+

1 个答案:

答案 0 :(得分:1)

您可以使用ORDER BYLIMIT

执行此操作
SELECT playerName, Sum(score) AS sumS
FROM table1
GROUP BY playerName
ORDER BY sumS DESC
LIMIT 1;

在tie的情况下,这将只返回其中一行。如果你想要所有这些,那么一种方法是:

SELECT playerName, Sum(score) AS sumS
FROM table1 t1
GROUP BY playerName
HAVING sumS = (SELECT Sum(tt1.score)
               FROM table1 tt1
               WHERE tt1.playerName = t1.playerName
               ORDER BY sumS DESC
               LIMIT 1
              );