我有这个User
表:
+----------+-------+
| Username | Value |
+----------+-------+
| User4 | 2 |
| User1 | 3 |
| User3 | 1 |
| User2 | 6 |
| User4 | 2 |
+----------+-------+
我执行此查询来获取前 2 个的总和:
SELECT Username, SUM(Value) AS Sum
FROM User
GROUP BY Username
ORDER BY Sum DESC
LIMIT 0, 2
这给了我结果:
+----------+-----+
| Username | Sum |
+----------+-----+
| User2 | 6 |
| User4 | 4 |
+----------+-----+
我正在寻找的是再一行给出所有值的总和,例如:
+----------+-----+
| Username | Sum |
+----------+-----+
| User2 | 6 |
| User4 | 4 |
| All | 14 |
+----------+-----+
有什么办法可以实现这一点吗?最好没有任何程序。
最佳答案
您可以使用WITH ROLLUP
修饰符:
SELECT COALESCE(Username, 'All'), SUM(Value) AS Sum
FROM User
GROUP BY Username WITH ROLLUP
ORDER BY Sum DESC
或者,如果您只想要前 2 个以及所有的总和:
SELECT Username, s
FROM (
SELECT Username, s
FROM (
SELECT COALESCE(Username, 'All') AS Username, SUM(Value) AS s
FROM User
GROUP BY Username WITH ROLLUP ) AS t
ORDER BY s DESC
LIMIT 0, 3) AS s
ORDER BY IF(Username = 'All', 0, s) DESC
关于MySQL 有限结果后的一行求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35938288/