HIVESQL-列转行&行转列(初级版)

一、列转行:

列数据:
在这里插入图片描述
转换后行数据:
在这里插入图片描述

方法:通过union all 实现

select userid, '语文' as subjectName ,chinese_score as socre  from score
union all 
select userid, '数学' as subjectName ,math_score as socre  from score
union all 
select userid, '英语' as subjectName ,english_score as socre  from score
union all 
select userid, '政治' as subjectName ,politics_score as socre  from score

二、行转列:

行数据:
在这里插入图片描述
转化后列数据:
在这里插入图片描述

方法一:case when … then …

select userid,
sum(case  when subjectName='语文' then score else 0 end )as '语文',
sum(case  when subjectName='数学' then score else 0 end )as '数学',
sum(case  when subjectName='英语' then score else 0 end )as '英语',
sum(case  when subjectName='政治' then score else 0 end )as '政治'
from score
group by userid;

方法二:sum(if())

select userid,
sum(if(subjectName='语文' , score , 0 ))as '语文',
sum(if(subjectName='数学' , score , 0 ))as '数学',
sum(if(subjectName='英语' , score , 0 ))as '英语',
sum(if(subjectName='政治' , score , 0 ))as '政治'
from score
group by userid;

[参考文章]:
http://www.360doc.com/content/21/0614/01/37253146_981925362.shtml

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值