第八章_函数【explode、lateral view、列转行】

1. explode (遍历集合 UDTF函数)
说明 : 将hive 中array 数据遍历成多行, map 遍历成 多行、多列(key,value)
注意 : 1. udtf 只支持 select 子语句中有一个表达式
          select explode(array) ✔️️
          select id,explode(array) ❌

2. explode(array|map)
          takes an array or a map as a parameter 只能接受一个 array或者map的参数

示例 :
复制代码
示例 :
        -- 1. array
        select explode(split('da,wang,lai,le',','));
        -- 2. map
        maptab.name     maptab.friend
        刘备    {"关羽":120,"山西":null}
        曹操    {"许褚":20}
        孙权    {"吕蒙":null}
        -- 执行sql
        select explode(friend) from maptab;
        -- 结果
        key     value
        关羽    120
        山西    NULL
        许褚    20
        吕蒙    NULL
     -- 3. json
     select explode(split(get_json_object('{"code":"7,6"}','$.code'),','));
     -- 结果
     7
     6
复制代码

2. lateral view (侧视图)
1. 语法 : lateral view udtf(expression) tablealias as columnalias
          expression : 数据类型只能为 array或map
    2. 说明 : 将 udtf函数生成的多行数据,作为一个表(视图)使用
3. 注意 : lateral view udtf 不能和where 一起使用
-- 示例
复制代码
-- 示例
需求 : 将json中的code值,拆分成多行
样例数据:
    id codeJson
    1  {"code":"7,6"}
需求预期:
    id code
    1  7
    1  6

select
t1.id
,t2.reason
from (
    SELECT    id
             ,split(get_json_object(codeJson,'$.code'),',') as arr_reason
             ,substr(createtime,1,10) as createdate-- 创建日期
    FROM ods_tab
    where dt = '9999-99-99'
    and user_id = '0001'
    and substr(createtime,1,10) = '${zdt.addDay(-1).format("yyyy-MM-dd")}'
) as t1
lateral view explode(arr_reason) t2 as reason

-- 1. lateral view explode 无法与where 一起使用
复制代码

3. 示例(列转行) : 
复制代码
-- 人员表
    select * from arraytab;
    arraytab.name   arraytab.friends
    刘备1   ["关羽","张飞","马超","诸葛亮","黄忠","赵云"]
    曹操1   ["许褚","荀彧","司马懿"]
    -- 操作sql
    select name,friend from arraytab
    lateral view explode(friends) t1 as friend;
    -- 结果
    name    friend
    刘备1   关羽
    刘备1   张飞
    刘备1   马超
    刘备1   诸葛亮
    刘备1   黄忠
    刘备1   赵云
    曹操1   许褚
    曹操1   荀彧
    曹操1   司马懿
复制代码

 


posted @   学而不思则罔!  阅读(477)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
点击右上角即可分享
微信分享提示