hive 的 lateral view用法以及注意事项
1. lateral view 簡介
??hive函數 lateral view 主要功能是將原本匯總在一條(行)的數據拆分成多條(行)成虛擬表,再與原表進行笛卡爾積,從而得到明細表。配合UDTF函數使用,一般情況下經常與explode函數搭配,explode的操作對象(列值)是 ARRAY 或者 MAP ,可以通過 split 函數將 String 類型的列值轉成 ARRAY 來處理。
【語法格式】
select col_A,col_B,tmp_table.tmp_col from test_table lateral view explode(split(col_C,'分隔符')) tmp_table as tmp_col where partition_name='xxx';【說明】
col_A,col_B,col_C: 都是原表 test_table 的列(字段);
tmp_table:explode形成的新虛擬表,可以不寫;
tmp_col:explode 形成的新列(字段);
2. 實操
2.1 建表(hive)
??創建一個“部門利潤表”,按照日期分區,一共三個字段,“部門編號”、“部門層級樹”、“利潤(萬元)”。DDL語句如下:
drop table if exists zero_test_01: create table zero_test_01 (DEPT_NO string comment'部門編號',DEPT_TREE string comment'部門層級樹',BENIFIT int comment'利潤(萬元)' ) comment '測試-部門利潤表' partitioned by (deal_date string comment '日期分區' ) stored as orc;【字段說明】:DEPT_TREE 字段是按照“一級部門編號.二級部門編號.三級部門編號” 模式進行取值的。
2.2 插入數據
??往“20220516”分區中插入三條數據。
alter table zero_test_01 drop if exists partition (DEAL_DATE='20220516'); insert into table zero_test_01 partition (DEAL_DATE='20220516') select '101','A.A1.101',50; insert into table zero_test_01 partition (DEAL_DATE='20220516') select '102','A.A1.102',20; insert into table zero_test_01 partition (DEAL_DATE='20220516') select '201','A.A2.201',80;| 101 | A.A1.101 | 50 |
| 102 | A.A1.102 | 20 |
| 201 | A.A2.201 | 80 |
2.3 轉成多行
??利用 lateral view 和 explode 函數將 DEPT_TREE(部門層級樹) 列按照“.”分割轉成多行,通過結果可以看到,lateral view函數將 “部門層級樹” 字段炸開進行了擴展,每個部門(DEPT_NO)都有與之對應的利潤(BENIFIT),從三行數據直接變成9行數據。
select tmp_dept_no as DEPT_NO, BENIFIT from zero_test_01 LATERAL VIEW explode (split(DEPT_TREE, '\\.')) tmp as tmp_dept_no where DEAL_DATE='20220516';| A | 80 |
| A2 | 80 |
| 201 | 80 |
| A | 20 |
| A1 | 20 |
| 102 | 20 |
| A | 50 |
| A1 | 50 |
| 101 | 50 |
2.4 匯總求和
??對部門利潤進行向上匯總求和,可以看到每個部門的總利潤。
select tmp_dept_no as DEPT_NO, sum(BENIFIT) as BENIFIT from zero_test_01 LATERAL VIEW explode (split(DEPT_TREE, '\\.')) tmp as tmp_dept_no where DEAL_DATE='20220516' group by tmp_dept_no;| A | 150 |
| A1 | 70 |
| A2 | 80 |
| 101 | 50 |
| 102 | 20 |
| 201 | 80 |
總結
以上是生活随笔為你收集整理的hive 的 lateral view用法以及注意事项的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 案例 | 中央企业数字化转型实践
- 下一篇: later与late 的区别