Hive学习—行列转换

智者的梦再美,也不如愚人实干的脚印。供学习HSQL的童鞋们参考!

在工作学习中,往往需要对查询的表结构进行简单的行转列或列转行的优化

列转行

表数据如图,表名customer_details
在这里插入图片描述
要求:查询每个国家,女性,男性的人数,如图
在这里插入图片描述
我们很容易通过以下语句查出结果,但是格式和目标还需要转换下

select country,gender,count(*) as people from customer_details group by country,gender;

在这里插入图片描述

方法一(易于理解)

查出每个国家的男性人数作为临时表1,查出每个国家的女性人数作为临时表2,然后通过country字段来inner join实现左右连接

临时表1

select country,count(*) as female from customer_details where gender='Female' group by country

在这里插入图片描述
临时表2

select country,count(*) as female from customer_details where gender='Female' group by country

在这里插入图片描述
连接

select a.country,female,male from
(select country,count(*) as female from customer_details where gender='Female' group by country)a 
join 
(select country,count(*) as male from customer_details where gender='Male' group by country)b 
on
a.country=b.country
方法二(效率高)

利用sum,if函数计算分组时男性,女性的人数

select country,
sum(if(gender='Male',1,0)) as male,
sum(if(gender='Female',1,0)) as female
from customer_details
group by country

在这里插入图片描述

方法三(冷门)

分组,利用collect_list集合的size方法获取性别的数量

select a.country,female,male from
(select country,size(collect_list(gender)) as female from customer_details where gender='Female' group by country)a 
join 
(select country,size(collect_list(gender)) as male from customer_details where gender='Male' group by country)b 
on
a.country=b.country

为方便演示行转列,将上述的查询结果作为临时视图 tmpview

行转列

主要是利用union/union all实现上下连接

select country,'Female' as gender, female as people from tmpview 
union all
select country,'Male' as gender,male as people from tmpview

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值