如何把mysql的列修改成行显示数据简单实现

时间:2021-03-07 10:32:53

如何把mysql的列修改成行显示数据简单实现

 

如何把mysql的列修改成行显示数据简单实现

创建测试表:

   1: DROP TABLE IF EXISTS `test`;
   2: CREATE TABLE `test` (
   3:   `year` int(11) DEFAULT NULL,
   4:   `month` int(11) DEFAULT NULL,
   5:   `amount` double DEFAULT NULL
   6: ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

插入数据:

   1: INSERT INTO `test` VALUES ('1991', '1', '1.1');
   2: INSERT INTO `test` VALUES ('1991', '2', '1.2');
   3: INSERT INTO `test` VALUES ('1991', '3', '1.3');
   4: INSERT INTO `test` VALUES ('1991', '4', '1.4');
   5: INSERT INTO `test` VALUES ('1992', '1', '2.1');
   6: INSERT INTO `test` VALUES ('1992', '2', '2.2');
   7: INSERT INTO `test` VALUES ('1992', '3', '2.3');
   8: INSERT INTO `test` VALUES ('1992', '4', '2.3');

 

看到题目要求,仔细想想可以:

利用SUM(IF()) 生成列 + WITH ROLLUP 生成汇总行,并利用 IFNULL将汇总行标题显示为 Total_num

实现
SQL代码块如下:

   1: select year,
   2:     sum(if(month=1,amount,0)) as "M1",
   3:     sum(if(month=2,amount,0)) as "M2",
   4:     sum(if(month=3,amount,0)) as "M3",
   5:     sum(if(month=4,amount,0)) as "M4"
   6: from test
   7: GROUP by year;

效果如下:

如何把mysql的列修改成行显示数据简单实现