【大数据Hive3.x数仓开发】HiveSQL行转列应用-多行转多列case when&多行转单列concat_ws,collect

1 行转列:多行转多列–case when 函数

实际需求:统计得到每小时UV、PV、IP的个数,做折线图,但是表中的数据存储格式不利于直接查询展示。
多行转多列:
在这里插入图片描述

功能:实现对数据的判断,根据条件,不同的情况返回不同的结果,类似于java的switch case功能。
两种语法:

case
when 条件 then value1
else 默认值
end as 别名
--先指定了列
casewhen V1 then value1
else 默认值
end as 别名

所以图示的多行转多列实现:
在这里插入图片描述

2 行转列:多行转单列–concat_ws,collect

在这里插入图片描述

数据拼接

拼接相关函数,立马想到
concat:用于实现字符串拼接,但是不可指定分隔符。
特点:任意一个元素null,结果null.

concat_ws函数:可指定分隔符。
特点:任意一个元素不null,结果不null。

数据收集

collect_list将多行合并一行,不去重。(list表面数据有序有索引,可重)
collect_set:将多行合并一行,去重

代码给出从建表到实现多行转单列:

--建表
creat table a(
			col1 string
			,col2 string
			,col3 int
)row format delimited fields terminated by '\t';
--加载数据导到表
load data local inpath '/root/hivedata/a.txt' into table a;
--实现
select 
	col1
	,col2
	,concat_ws(',',collect_list(cast(col3 as string))) as col3
from a
group by 
	col1
	,col2;

注:cast(col3 as string)类型强制转换 通过describe function extended concat_ws;可以知道函数只接受string或者arrag(string)类型数据。

HiveSQL列转行应用-union\explode函数详解

  • 0
    点赞
  • 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、付费专栏及课程。

余额充值