MySQL Grand Total Rows和Columns

时间:2017-08-02 13:04:26

标签: mysql sum rollup totals

我不仅要总计一组数据的主要分组,还要总计下一个分组级别。在我的例子中,ROLLUP总计了一个月(行)的值,但我还想总计销售代表(列)的值。

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

我迄今为止的最大努力:

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

制作以下内容

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

理想情况下,我希望它显示

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

1 个答案:

答案 0 :(得分:0)

E.g。 (虽然在实践中我可能会处理应用程序代码中的摘要数据):

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