MySQL实现pivot行转列

1.创建表: 

Create Table

CREATE TABLE `pivot` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `salary` double NOT NULL,
  `year` varchar(4) NOT NULL,
  `name` varchar(10) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8

 2.插入数据:

insert into `pivot` (`id`, `salary`, `year`, `name`) values('1','100','2016','tom');
insert into `pivot` (`id`, `salary`, `year`, `name`) values('2','200','2017','tom');
insert into `pivot` (`id`, `salary`, `year`, `name`) values('3','300','2018','tom');
insert into `pivot` (`id`, `salary`, `year`, `name`) values('4','400','2019','tom');
insert into `pivot` (`id`, `salary`, `year`, `name`) values('5','123','2016','nicole');
insert into `pivot` (`id`, `salary`, `year`, `name`) values('6','234','2017','nicole');
insert into `pivot` (`id`, `salary`, `year`, `name`) values('7','345','2018','nicole');
insert into `pivot` (`id`, `salary`, `year`, `name`) values('8','456','2019','nicole'); 

                                            

3.实现行转列方式一: 

  SELECT `name`,
    SUM(salary1) '2016',
    SUM(salary2) '2017',
    SUM(salary3) '2018',
    SUM(salary4) '2019'
FROM (
    SELECT `name`, 
             
              CASE WHEN `year`= '2016' THEN 
                   salary 
              END salary1, 
              CASE WHEN `year`= '2017' THEN 
                    salary 
              END salary2, 
              CASE WHEN `year` = '2018' THEN 
                   salary 
               END salary3,
           CASE WHEN `year` = '2019' THEN 
                   salary 
               END salary4
           FROM pivot) t 
GROUP BY `name`;

4:实现行转列方式二:

SELECT `name`,
    SUM(IF (`year`='2016',salary,NULL)) '2016',
    SUM(IF (`year`='2017',salary,NULL)) '2017',
    SUM(IF (`year`='2018',salary,NULL))'2018',
    SUM(IF (`year`='2019',salary,NULL)) '2019'
FROM `pivot`
GROUP BY `name`; 

猜你喜欢

转载自blog.csdn.net/sperospera/article/details/89199806