【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);

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章