MySQL有限结果后的一行总和
MySQL one row of sum after limited results
我有这个 User
table:
+----------+-------+
| 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 |
+----------+-----+
有什么办法可以实现吗?最好不用任何程序。
使用联合
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
使用 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)
您可以使用 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
我有这个 User
table:
+----------+-------+
| 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 |
+----------+-----+
有什么办法可以实现吗?最好不用任何程序。
使用联合
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
使用 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)
您可以使用 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