MySQL从按字段分组的派生值中选择最大值

时间:2014-03-06 15:21:00

标签: mysql

我有一张简单的表

==============================
| playerId | score1 | score2 |
|============================|
|        1 |      1 |      2 |
|        1 |      5 |      1 |
|        2 |      6 |      6 |
|        2 |      1 |      3 |
==============================

我想总结得分1和得分2并找出哪个得分较高的球员,所以这就是我所在的地方

SELECT MAX(sum(score1) + sum(score2)) FROM player_scores GROUP BY playerId

但是我得到了

  

1111 - 无效使用群组功能

2 个答案:

答案 0 :(得分:3)

简单而有效。

SELECT playerId, SUM( score1 + score2 )
FROM `test`
GROUP BY playerId
ORDER BY 2 DESC
LIMIT 1 

答案 1 :(得分:1)

尝试使用子选择内部选择我得到总和,在外部选择我已经计算了两个得分的最大值

SELECT t.*,MAX(t.score1) + MAX(t.score2) `total` FROM
(
SELECT playerId,sum(score1)score1 ,sum(score2) score2
FROM player_scores 
GROUP BY playerId
) t
GROUP BY t.playerId

See fiddle Demo