SQL數據單條轉多條(Lateral View)


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”


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM