Search code examples
mysqlsqlmariadbmariasql

MySQL one row of sum after limited results


I've got this User table:

+----------+-------+
| Username | Value |
+----------+-------+
| User4    |     2 |
| User1    |     3 |
| User3    |     1 |
| User2    |     6 |
| User4    |     2 |
+----------+-------+

And I do this query to get the top 2's sums:

SELECT Username, SUM(Value) AS Sum
FROM User
GROUP BY Username
ORDER BY Sum DESC
LIMIT 0, 2

Which gives me as a result:

+----------+-----+
| Username | Sum |
+----------+-----+
| User2    |   6 |
| User4    |   4 |
+----------+-----+

What I'm looking for is one more row giving the sum of all the values, like:

+----------+-----+
| Username | Sum |
+----------+-----+
| User2    |   6 |
| User4    |   4 |
| All      |  14 |
+----------+-----+

Is there any way to achieve that? Preferably with no procedures.


Solution

  • You can use WITH ROLLUP modifier:

    SELECT COALESCE(Username, 'All'), SUM(Value) AS Sum
    FROM User
    GROUP BY Username WITH ROLLUP
    ORDER BY Sum DESC 
    

    or, if you want just top 2 along with the sum of all:

     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