Lateral View
更新時間:2019-02-13 11:56:02
Lateral View和split,explode等UDTF一起使用,它能夠將一行數據拆成多行數據,並在此基礎上對拆分後的數據進行聚合。
單個Lateral View語句
語法定義如下:
lateralView: LATERAL VIEW [OUTER] udtf(expression) tableAlias AS columnAlias (',' columnAlias) * fromClause: FROM baseTable (lateralView)*
說明如下:
- Lateral view outer:當table function不輸出任何一行時,對應的輸入行在Lateral view結果中依然保留,且所有table function輸出列爲null。
示例如下:
假設我們有一張表pageAds,它有兩列數據,第一列是pageid string,第二列是adid_list,即用逗號分隔的廣告ID集合。
string pageid | Array<int> adid_list |
---|---|
“front_page” | [1, 2, 3] |
“contact_page” | [3, 4, 5] |
需求是要統計所有廣告ID在所有頁面中出現的次數,實現過程如下所示。
- 拆分廣告ID,如下所示:
SELECT pageid, adid FROM pageAds LATERAL VIEW explode(adid_list) adTable AS adid;
執行結果如下:
string pageid int adid “front_page” 1 “front_page” 2 “front_page” 3 “contact_page” 3 “contact_page” 4 “contact_page” 5 - 進行聚合的統計,語句如下:
SELECT adid, count(1) FROM pageAds LATERAL VIEW explode(adid_list) adTable AS adid GROUP BY adid;
執行結果如下:
int adid count(1) 1 1 2 1 3 2 4 1 5 1
多個Lateral View語句
一個from語句後可以跟多個Lateral View語句,後面的Lateral View語句能夠引用它前面的所有表和列名。
以下面的表爲例:
Array<int> col1 | Array<string> col2 |
---|---|
[1, 2] | [“a”, “b”, “c”] |
[3, 4] | [“d”, “e”, “f”] |
- 執行單個語句:
SELECT myCol1, col2 FROM baseTable LATERAL VIEW explode(col1) myTable1 AS myCol1;
執行結果如下所示:
int mycol1 Array<string> col2 1 [“a”, “b”, “c”] 2 [“a”, “b”, “c”] 3 [“d”, “e”, “f”] 4 [d”, “e”, “f”] - 加上一個Lateral View語句,如下所示:
SELECT myCol1, myCol2 FROM baseTable LATERAL VIEW explode(col1) myTable1 AS myCol1 LATERAL VIEW explode(col2) myTable2 AS myCol2;
int myCol1 string 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” 來源: https://help.aliyun.com/document_detail/87722.html?spm=a2c4g.11186623.2.9.41a11230wnHcpj