码迷,mamicode.com
首页 > 数据库 > 详细

SQL分组多列统计(GROUP BY后按条件分列统计) -转

时间:2015-04-17 17:19:39      阅读:400      评论:0      收藏:0      [点我收藏+]

标签:

今天在园子里看到个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

 

SQL分组多列统计(GROUP BY后按条件分列统计) -转

标签:

原文地址:http://www.cnblogs.com/sarahs/p/4435089.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!