简体   繁体   中英

MySQL select max value from derived values grouped by field

I have a simple table

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

I want to sum fields score1 and score2 and find out which player has higher score, so this is where I'm at

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

But I get

1111 - Invalid use of group function

Simple and works.

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

Try this with a sub select inner select i get the sum and in outer select i have calculated the max of both scores

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM