Search code examples
mysqlsumrollup

MySQL Grand Total Rows and Columns


I would like to not only total the main grouping of a set of data, but also total the next grouping level. In my case, the ROLLUP totals the values for a month (rows) but I would also like to total the values for sales rep (columns).

http://sqlfiddle.com/#!9/60608/1

My best effort to date:

CREATE TABLE IF NOT EXISTS SALES (
Month INT(3),
Rep CHAR(60),
Val DECIMAL (20 , 6 )
);

INSERT INTO SALES (Month, Rep, Val) VALUES
('9','Rep1',10),
('9','Rep1',20),
('9','Rep2',20),
('9','Rep2',30),
('9','Rep2',40),
('10','Rep1',50),
('10','Rep1',60),
('10','Rep2',70),
('11','Rep2',80);

SELECT Month, IFNULL(Rep, 'Total'), SUM(Val) As TotalValue
FROM SALES 
GROUP BY FIELD(Month,
    '9',
    '10',
    '11') ASC, Rep WITH ROLLUP

Produces the following

9   Rep1    30
9   Rep2    90
9   Total   120
10  Rep1    110
10  Rep2    70
10  Total   180
11  Rep2    80
11  Total   80
11  Total   380

Ideally I would like it to show

9   Rep1    30
9   Rep2    90
9   Total   120
10  Rep1    110
10  Rep2    70
10  Total   180
11  Rep2    80
11  Total   80
11  Total   380
0   Rep1   140
0   Rep2   240

Solution

  • E.g. (although in practice I'd probably handle the summary data in application code):

    SELECT * FROM (SELECT month,rep,SUM(val) val FROM sales GROUP BY month,rep WITH ROLLUP) x
    UNION
    SELECT 0,rep, SUM(val) FROM sales GROUP BY rep;
    +-------+------+------------+
    | month | rep  | val        |
    +-------+------+------------+
    |     9 | Rep1 |  30.000000 |
    |     9 | Rep2 |  90.000000 |
    |     9 | NULL | 120.000000 |
    |    10 | Rep1 | 110.000000 |
    |    10 | Rep2 |  70.000000 |
    |    10 | NULL | 180.000000 |
    |    11 | Rep2 |  80.000000 |
    |    11 | NULL |  80.000000 |
    |  NULL | NULL | 380.000000 |
    |     0 | Rep1 | 140.000000 |
    |     0 | Rep2 | 240.000000 |
    +-------+------+------------+