本文主要是介绍sql-行转列2(转置),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
行转列的常规做法是,group by+sum(if())【或count(if())】
例题:
表table如下:
DDate | shengfu |
---|---|
2015-05-09 | 胜 |
2015-05-09 | 胜 |
2015-05-09 | 负 |
2015-05-09 | 负 |
2015-05-10 | 胜 |
2015-05-10 | 负 |
2015-05-10 | 负 |
如果要生成下列结果, 该如何写sql语句?
DDate | 胜 | 负 |
---|---|---|
2015-05-09 | 2 | 2 |
2015-05-10 | 1 | 2 |
--建表
create table table1(DDate string, shengfu string) ;
insert overwrite table table1 values ('2015-05-09', "胜"),('2015-05-09', "胜"),('2015-05-09', "负"),('2015-05-09', "负"),('2015-05-10', "胜"),('2015-05-10', "负"),('2015-05-10', "负");select DDate,,SUM(case when shengfu = '胜' then 1 else 0 end) `胜`,SUM(case when shengfu = '负' then 1 else 0 end) `负`
from table1
group by DDate;
这篇关于sql-行转列2(转置)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!