sql-行转列(转置)

- 行转列的常规做法是,group by+sum(if())【或count(if())】

例题

已知

year month amount
1991 1 1.1
1991 2 1.2
1991 3 1.3
1991 4 1.4
1992 1 2.1
1992 2 2.2
1992 3 2.3
1992 4 2.4

查成这样一个结果

year m1 m2 m3 m4
1991 1.1 1.2 1.3 1.4
1992 2.1 2.2 2.3 2.4

解答

sql 复制代码
use test_sql;
set hive.exec.mode.local.auto=true;
create table table2(year int,month int ,amount double) ;
insert overwrite table table2 values
           (1991,1,1.1),
           (1991,2,1.2),
           (1991,3,1.3),
           (1991,4,1.4),
           (1992,1,2.1),
           (1992,2,2.2),
           (1992,3,2.3),
           (1992,4,2.4);
select * from table2;


--行转列
--常规做法是,group by+sum(if())
--SQLserver中有pivot专门用来行转列
--原始写法
select 
	year
    ,sum(a) as m1
    ,sum(b) as m2
    ,sum(c) as m3
    ,sum(d) as m4
from(
	select 
		*
        ,if(month=1,amount,0) a
        ,if(month=2,amount,0) b
        ,if(month=3,amount,0) c
        ,if(month=4,amount,0) d
    from table2 ) t
group by t.year;
--简化写法
select 
	year,
	,sum(if(month=1,amount,0)) m1
	,sum(if(month=2,amount,0)) m2
    ,sum(if(month=3,amount,0)) m3
    ,sum(if(month=4,amount,0)) m4
from table2
group by year;
相关推荐
RestCloud9 小时前
SQL Server到Hive:批处理ETL性能提升30%的实战经验
数据库·api
RestCloud9 小时前
为什么说零代码 ETL 是未来趋势?
数据库·api
ClouGence11 小时前
CloudCanal + Paimon + SelectDB 从 0 到 1 构建实时湖仓
数据库
DemonAvenger18 小时前
NoSQL与MySQL混合架构设计:从入门到实战的最佳实践
数据库·mysql·性能优化
AAA修煤气灶刘哥1 天前
后端人速藏!数据库PD建模避坑指南
数据库·后端·mysql
RestCloud1 天前
揭秘 CDC 技术:让数据库同步快人一步
数据库·api
得物技术2 天前
MySQL单表为何别超2000万行?揭秘B+树与16KB页的生死博弈|得物技术
数据库·后端·mysql
可涵不会debug2 天前
【IoTDB】时序数据库选型指南:工业大数据场景下的技术突围
数据库·时序数据库
ByteBlossom2 天前
MySQL 面试场景题之如何处理 BLOB 和CLOB 数据类型?
数据库·mysql·面试