MySQL 总计行数和列数
MySQL Grand Total Rows and Columns
我不仅要汇总一组数据的主分组,还要汇总下一级分组。在我的例子中,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
例如(尽管实际上我可能会在应用程序代码中处理摘要数据):
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 |
+-------+------+------------+
我不仅要汇总一组数据的主分组,还要汇总下一级分组。在我的例子中,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
例如(尽管实际上我可能会在应用程序代码中处理摘要数据):
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 |
+-------+------+------------+