《Hive官方文档》Hive - Lateral View 与 explode() 结合使用

官网链接:Hive官方文档

一、Lateral View 语法

lateralView: 
LATERAL VIEW udtf(expression) tableAlias AS columnAlias (',' columnAlias)*

fromClause: 
FROM baseTable (lateralView)*

Lateral View用于UDTF(user-defined table generating functions)中将行转成列,例如explode()。

二、示例

1.单个 Lateral View

以下名为pageAds的基本表。它有两列:pageid(页面名称)和adid_list(页面上显示的广告数组):

Column nameColumn type
pageidSTRING
adid_listArray<int>

有两行的数据:

pageidadid_list
front_page[1, 2, 3]
contact_page[3, 4, 5]

计算广告在所有页面上展示的总次数。

带有explode()的Lateral View可将adid_list转换为单独的行:

SELECT 
    pageid, 
    adid
FROM pageAds 
LATERAL VIEW explode(adid_list) adTable AS adid;

结果输出将是

pageid (string)adid (int)
"front_page"1
"front_page"2
"front_page"3
"contact_page"3
"contact_page"4
"contact_page"5

然后,为了计算特定广告的展示次数,可以使用 count/group by:

SELECT 
    adid, 
    count(1)
FROM pageAds 
LATERAL VIEW explode(adid_list) adTable AS adid
GROUP BY adid;
adidcount(1)
11
21
32
41
51

2.多个 Lateral View

FROM 子句可以具有多个 LATERAL VIEW 子句。随后的 LATERAL VIEWS 可以引用 LATERAL VIEW 左侧出现的任何表中的列。

例如:

SELECT 
    * 
FROM exampleTable
LATERAL VIEW explode(col1) myTable1 AS myCol1
LATERAL VIEW explode(myCol1) myTable2 AS myCol2;

LATERAL VIEW 子句按它们出现的顺序应用。例如基本表:

Array<int> col1Array<string> col2
[1, 2][a", "b", "c"]
[3, 4][d", "e", "f"]

The query:

SELECT 
    myCol1, col2 
FROM baseTable
LATERAL VIEW explode(col1) myTable1 AS myCol1;

将产生如下结果:

int mycol1Array<string> col2
1[a", "b", "c"]
2[a", "b", "c"]
3[d", "e", "f"]
4[d", "e", "f"]

多个 Lateral View 的HQL查询:

SELECT 
    myCol1, 
    myCol2 
FROM baseTable
LATERAL VIEW explode(col1) myTable1 AS myCol1
LATERAL VIEW explode(col2) myTable2 AS myCol2;

将产生如下结果:

int myCol1string myCol2
1"a"
1"b"
1"c"
2"a"
2"b"
2"c"
3"d"
3"e"
3"f"
4"d"
4"e"
4"f"
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值