【SQL32】行转列

行转列
怎么把下面的表tb_tab

year    month   amount
2017    1       1.1
2017    2       1.2
2017    3       1.3
2017    4       1.4
2018    1       2.1
2018    2       2.2
2018    3       2.3
2018    4       2.4

查成这样1个结果

year    m1      m2      m3      m4
2017    1.1     1.2     1.3     1.4
2018    2.1     2.2     2.3     2.4

解决:

select year
      ,sum(case when month = 1 then amount end) as m1
      ,sum(case when month = 2 then amount end) as m2
      ,sum(case when month = 3 then amount end) as m3
      ,sum(case when month = 4 then amount end) as m4
  from tb_tab
 group by year
;

year	m1	m2	m3	m4
2017	1.1	1.2	1.3	1.4
2018	2.1	2.2	2.3	2.4


备注:建表和数据
create table tb_tab(year int,month int,amount decimal(10,2));
insert into tb_tab values(2017,1,1.1);
insert into tb_tab values(2017,2,1.2);
insert into tb_tab values(2017,3,1.3);
insert into tb_tab values(2017,4,1.4);
insert into tb_tab values(2018,1,2.1);
insert into tb_tab values(2018,2,2.2);
insert into tb_tab values(2018,3,2.3);
insert into tb_tab values(2018,4,2.4);

猜你喜欢

转载自blog.csdn.net/debimeng/article/details/104300926