SQL分組多列統計(GROUP BY后按條件分列統計) -轉


今天在園子里看到個group by 分組多列統計的例子,轉走給大家分享一下:

create table tests (year datetime year to year,type char(1),value int);
alter table tests alter colomn year int;

insert into tests values (2015,1,100);
insert into tests values (2015,2,200);
insert into tests values (2016,1,150);
insert into tests values (2016,2,300);
insert into tests values (2016,3,100);

YEAR TYPE VALUE
2015 1 100
2015 2 200
2016 1 150
2016 2 300
2016 3 100

 

 

 

 

 

轉為:

YEAR TYPE1 TYPE2 TYPE3
2015 100 200 0
2016 150 300 100

 

 

 

 

這時候我們除了用到GROUP BY之外還需要CASE WHEN,SQL如下:

SELECT year,
 SUM(CASE WHEN type=1 THEN value ELSE 0 END) as type1,
 SUM(CASE WHEN type=2 THEN value ELSE 0 END) as type2,
 SUM(CASE WHEN type=3 THEN value ELSE 0 END) as type3,
 FROM table_test GROUP BY year

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM