SQL分组多列统计(GROUP BY后按条件分列统计) -转
2015-04-17 15:34
459 查看
今天在园子里看到个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);
转为:
这时候我们除了用到GROUP BY之外还需要CASE WHEN,SQL如下:
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 |
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后按条件分列统计)
- SQL分组多列统计(GROUP BY后按条件分列统计)
- 【数据库】SQL分组多列统计(GROUP BY后按条件分列统计)
- 两个条件分组统计sql
- sql分组统计查询 count带条件
- sql分组按条件统计count case when then
- sql GROUP BY 分组统计
- sq更新语句条件子查询中有分组统计的sql,导致错误1093
- SQL 统计分组 Group By和Compute By的整理
- Excel 中使用SQL 语句查询数据(八)-----用Group by 进行分组统计
- sql的分组统计与group by 日期的处理
- group by分组统计SQL语句
- mysql按日期分组(group by)查询统计的时候,没有数据补0的解决办法。
- sql笔记-group by 统计功能
- mysql排序查询,多条件排序查询,聚合函数的使用,分组统计查询,
- SQL 中的单列数据到多列数据的转换,以及转换后的分组统计
- Oracle-SQL-group by-报错:不是单组分组函数
- Sql分组统计top-n或bottom-n
- mongodb mapredReduce 多个条件分组(group by)
- 用Sql语句怎么 将分组查询得到的记录数 统计出来