gpt4 book ai didi

MySQL 有限结果后的一行求和

转载 作者:行者123 更新时间:2023-11-29 07:21:41 24 4
gpt4 key购买 nike

我有这个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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com