sql语句——1.通过hue平台在hive里建表(creat table,join,lateral view,explode)

时间:2024-05-22 22:46:22

1.今天遇到的一个建表任务为例,需要将表里的机型列做映射后与源表合并,是建表经常会遇到的场景,分享代码如下:
create table oppo_os_pso.temp_20200806_xiao0051 as
select brand,region,a.model,b.phone_type,weekno, man_ratio, total_person_num
from oppo_os_pso.temp_20200806_xiao005 a
join
(select phone_type, model, model2
from oppo_os_pso.phone_type
LATERAL VIEW explode(split(model,’,’)) model as model2)b on a.model = b.model2
order by brand,region,a.model,b.phone_type,weekno;sql语句——1.通过hue平台在hive里建表(creat table,join,lateral view,explode)
2.然后我们可以拆解一下上述语句:
creat table 库.要建的表 as
select 列,列,列
from 源表1 a
join
(select 列,列,列 from 库.源表2
LATERAL VIEW explode ( split ( 列 , ‘,’ ) ) 列 as 列) b
on a.列 = b.列
order by 列,列,列

3.可能需要说明的点:
① 建表 creat table XXX as select XXX from XXX

② 映射 a join b on a.列 = b.列 (匹配上model机型的,返回b表的phon_type)
JOIN: 如果表中有至少一个匹配,则返回行
LEFT JOIN: 即使右表中没有匹配,也从左表返回所有的行
RIGHT JOIN: 即使左表中没有匹配,也从右表返回所有的行
FULL JOIN: 只要其中一个表中存在匹配,就返回行

③explode 作用为“将数组拆成多行”【将hive一行中复杂的array或者map结构拆分成多行】sql语句——1.通过hue平台在hive里建表(creat table,join,lateral view,explode)
④ lateral view 作用为将数组拆成两列前后对应的多行
lateral view能将一行数据拆分成多行数据,和split、explode等UDTF一起使用,在此基础上可以对拆分的数据进行聚合(lateral view首先为源表的每行调用UDTF,UDTF会把一行拆分成一行或者多行,lateral view在把结果组合,产生一个支持别名表的虚拟表)
sql语句——1.通过hue平台在hive里建表(creat table,join,lateral view,explode)
sql语句——1.通过hue平台在hive里建表(creat table,join,lateral view,explode)
示例说明:sql语句中【LATERAL VIEW explode(split(model,’,’)) model as model2】的作用其实很简单:model列有一些(机型A,机型B)的内容,通过这个语句转化为model2列:(机型A),(机型B);

其他大神使用经验:
Lateral View通常和UDTF一起出现,为了解决UDTF不允许在select字段的问题。
Multiple Lateral View可以实现类似笛卡尔乘积。
Outer关键字可以把不输出的UDTF的空结果,输出成NULL,防止丢失数据