Hive 行列转换

行列转换
列转行

使用 lateral view + explode(array|map)lateral view + inline(array_struct) 可以将列转换为行。

  • 单列转多行,降维(单列数组或键值对)

示例1:explode(array(...))

sql 复制代码
select ..., A
from T
lateral view explode(ARRAY_FIELD) as A;
sql 复制代码
select explode(`array`(88.2,98.3,67.1)) AS (price);

示例2:explode(map(...))

sql 复制代码
select ..., K, V
from T
lateral view explode(MAP_FIELD) as K, V;
sql 复制代码
select explode(`map`("java",56,"mysql",88,"javascript",66)) AS (subject, score);

示例3:inline(array_struct)

sql 复制代码
select ..., 
from T
lateral view inline(STRUCT_ARRAY_FIELD)V as F1,...,FN;
sql 复制代码
with tmp as (
select array(
	named_struct('name','henry','age',22,'is_member','true'),
	named_struct('name','pola','age',20,'is_member','true'),
	named_struct('name','ariel','age',19,'is_member','true')
   ) AS array_struct
)
select name,age,is_member
from tmp
lateral view inline(array_struct)V as name,age,is_member;

lateral view inline(array_struct)将结构体数组的每个元素都转化为一行,每一行都包含结构体字段的值.

前:

后:

  • 多列转多行
sql 复制代码
select ..., A
from T
lateral view explode(array|map(F1,...,FN))V as A;

示例:

sql 复制代码
SELECT name, class, Scores.subject, Scores.score
FROM Students
LATERAL VIEW EXPLODE(ARRAY(
	named_struct('subject','math','score',math_score),
	named_struct('subject','science','score',science_score)
	)
) V AS Scores;

前:

后:

行转列
  • 多行转多列
    条件聚合,通常用于将多行数据中满足条件的某个值聚合到单个行中。
sql 复制代码
select
		F1,...,
		sum(if(C1,0,V1)) as A1,
		sum(if(C2,0,V2)) as A2,
		sum(if(C3,0,V3)) as A3
	from TABLE_NAME
	group by F1,...
	
	drop table if exists lateral_view_stack_test1w;
	create table lateral_view_stack_test1w as
	select year,
		   sum(if(month(order_time)=1,order_amount,0)) as sum_jan,
		   sum(if(month(order_time)=2,order_amount,0)) as sum_feb,
		   sum(if(month(order_time)=3,order_amount,0)) as sum_mar,
		   sum(if(month(order_time)=4,order_amount,0)) as sum_apr,
		   sum(if(month(order_time)=5,order_amount,0)) as sum_may,
		   sum(if(month(order_time)=6,order_amount,0)) as sum_jun,
		   sum(if(month(order_time)=7,order_amount,0)) as sum_jul,
		   sum(if(month(order_time)=8,order_amount,0)) as sum_aug,
		   sum(if(month(order_time)=9,order_amount,0)) as sum_sep,
		   sum(if(month(order_time)=10,order_amount,0)) as sum_oct,
		   sum(if(month(order_time)=11,order_amount,0)) as sum_nov,
		   sum(if(month(order_time)=12,order_amount,0)) as sum_dec
	from hive_internal_par_regex_test1w
	where year>=2014
	group by year;
相关推荐
Acrelhuang19 分钟前
安科瑞5G基站直流叠光监控系统-安科瑞黄安南
大数据·数据库·数据仓库·物联网
消失在人海中1 小时前
数据仓库之 Atlas 血缘分析:揭示数据流奥秘
数据仓库
Hsu_kk1 小时前
Hive 查询用户连续三天登录的所有记录
数据仓库·hive·hadoop
houzhizhen1 天前
HiveMetastore 的架构简析
hive
数据要素X1 天前
【数据仓库】Hive 拉链表实践
大数据·数据库·数据仓库·人工智能·hive·hadoop·安全
LiamTuc2 天前
远程访问,通过JDBC连接到Beeline对Hive进行操作报错
数据仓库·hive·hadoop
songqq272 天前
sql中判断一个字段是否包含一个数据的方法有哪些?
数据库·hive·sql
zmd-zk2 天前
sql在hive和阿里云maxComputer的区别
数据库·hive·sql
油头少年_w2 天前
Hive操作库、操作表及数据仓库的简单介绍
数据仓库·hive
soso19682 天前
通过Flink读写云原生数据仓库AnalyticDB PostgreSQL版(ADB PG)数据
数据仓库·云原生·flink