简体   繁体   中英

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

Eg (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 |
+-------+------+------------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM