我有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 |
+----------+-----+
有没有办法实现这一目标?最好没有程序。
答案 0 :(得分:1)
使用UNION ALL执行此操作。
(SELECT Username, SUM(Value) AS Sum
FROM User
GROUP BY Username
ORDER BY Sum DESC
LIMIT 0, 2)
UNION ALL
(SELECT 'All', SUM(Value) AS Sum FROM User)
答案 1 :(得分:1)
您可以使用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
答案 2 :(得分:0)
使用union
SELECT Username, SUM(Value) AS Sum
FROM User
GROUP BY Username
ORDER BY Sum DESC
LIMIT 0, 2
union
SELECT'ALL', SUM(Value) AS Sum
FROM User