时间:2021-04-27 09:09:02 | 栏目:Mysql | 点击:次
创建测试表:
DROP TABLE IF EXISTS `test`; CREATE TABLE `test` ( `year` int(11) DEFAULT NULL, `month` int(11) DEFAULT NULL, `amount` double DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
插入数据:
INSERT INTO `test` VALUES ('1991', '1', '1.1'); INSERT INTO `test` VALUES ('1991', '2', '1.2'); INSERT INTO `test` VALUES ('1991', '3', '1.3'); INSERT INTO `test` VALUES ('1991', '4', '1.4'); INSERT INTO `test` VALUES ('1992', '1', '2.1'); INSERT INTO `test` VALUES ('1992', '2', '2.2'); INSERT INTO `test` VALUES ('1992', '3', '2.3'); INSERT INTO `test` VALUES ('1992', '4', '2.3');
看到题目要求,仔细想想可以:
利用SUM(IF()) 生成列 + WITH ROLLUP 生成汇总行,并利用 IFNULL将汇总行标题显示为 Total_num
实现
SQL代码块如下:
select year, sum(if(month=1,amount,0)) as "M1", sum(if(month=2,amount,0)) as "M2", sum(if(month=3,amount,0)) as "M3", sum(if(month=4,amount,0)) as "M4" from test GROUP by year;
效果如下: