0

我有这张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 |
+----------+-----+

有没有办法做到这一点?最好不用程序。

4

3 回答 3

2

您可以使用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
于 2016-03-11T10:55:03.557 回答
1

使用联合

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
于 2016-03-11T10:52:48.163 回答
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)
于 2016-03-11T10:54:05.490 回答