sql-行转列(转置)

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

例题
已知

yearmonthamount
199111.1
199121.2
199131.3
199141.4
199212.1
199222.2
199232.3
199242.4

查成这样一个结果

yearm1m2m3m4
19911.11.21.31.4
19922.12.22.32.4

解答

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;

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值