hive sql练习多行变多列

描述:表中记录了各年份各部门的平均绩效考核成绩
表结构:
a -- 年份
b -- 部门
c -- 绩效得分

表内容
t1.a    t1.b    t1.c
2014    B       9
2015    A       8
2014    A       10
2015    B       7

建表语句

create table t25(
  a string,
  b string,
  c int
)row format delimited
fields terminated by ',';
load data local inpath '/home/hivedata/t25.txt' into table t25;
with t1 as (
    select distinct a,concat_ws('',collect_set(concat(b,c)) over (partition by c)) temp from t25
    ),t2 as (select distinct a,
                     `if`(substr(temp,1,1)='A',substr(temp,2),null ) as col_A,
                     `if`(substr(temp,1,1)='B',substr(temp,2),null ) as col_B
                     from t1) select a,
                                     sum(case when col_A is not null then col_A end ) col_A,
                                     sum(case when col_B is not null then col_B end ) col_B
                                     from t2 group by a;

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
回答: 在Hive中,将多行转换为多列可以使用多种方法。其中一种方法是使用SQL语句中的UNION ALL操作符,将多个查询结果合并为一个结果集。例如,可以使用以下SQL语句将多行转换为多列: ``` select col1, 'c' as col2, col2 as col3 from col2row1 UNION ALL select col1, 'd' as col2, col3 as col3 from col2row1 UNION ALL select col1, 'e' as col2, col4 as col3 from col2row1; ``` 这个SQL语句将col2row1表中的数据按照指定的列进行组合,每个查询结果都会添加一个新的列,最终得到的结果集将包含多个列。\[2\] 另一种方法是使用Hive中的lateral view和explode函数。这个方法适用于一列中包含多个数据的情况,比如Map或array。可以使用以下SQL语句将多行转换为多列: ``` select col1, col2, lv.col3 as col3 from col2row2 lateral view explode(split(col3, ',')) lv as col3; ``` 这个SQL语句使用explode函数将col3列中的数据切分为多个行,并将其展示为多列的形式。\[3\] 总结起来,Hive中可以使用UNION ALL操作符或lateral view和explode函数来实现多行多列的操作。具体使用哪种方法取决于数据的结构和需求。 #### 引用[.reference_title] - *1* *2* *3* [Hive多行多列多列多行](https://blog.csdn.net/weixin_44870066/article/details/128006898)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值