gpt4 book ai didi

MySQL 总计行和列

转载 作者:行者123 更新时间:2023-11-30 21:55:18 25 4
gpt4 key购买 nike

我不仅要汇总一组数据的主要分组,还要汇总下一个分组级别。在我的例子中,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 |
+-------+------+------------+

关于MySQL 总计行和列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45461689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com