Hive系列(五)客戶需求千變萬化。。我都暈了---sql行轉列與列轉行總結(Hive版)

sql列轉行:

核心思想:列值轉列名:往往列值是幾個類別不是數值型

核心方法:case…when… | collect_list(列名)

案例一:

在這裏插入圖片描述
將上圖列值將其轉化爲下圖列名

country male female
china 24 38

通常情況下:列值多爲類別型,轉換爲列名後需要記數

法一:case…when…

select 
sum(case when gender='Female' then 1 else 0 end) as female,
sum(case when gender='Male' then 1 else 0 end) as male, country
from customer_details_copy group by country

法二:collect_list()

# size可以計算大小,concat_ws可以將多個列值合一起
with
t1 as (select size(collect_list(gender)) as female,country from customer_details_copy where gender='Female' group by country),
t2 as (select size(collect_list(gender)) as male,country from customer_details_copy where gender='Male' group by country)
select t1.country,t2.male,t1.female from t1 join t2 on t1.country = t2.country

sql行轉列:

核心思想:列名轉列值

將多個列名變成列值,那麼那一列需要起一個統一的列名,同時將列名對應的值變成新的列

核心方法: union | explode(split(列名))
(單列名的列值有多個數據,將每個數據打散成行)往往列名沒有列值

法一:union往往是多列名想要轉爲列值,除了explode的打散成行,還需要將多個列名對應的值也合起來抽象成新的列名

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-PNFCID5z-1592353385155)(C:%5CUsers%5Clenovo%5CAppData%5CRoaming%5CTypora%5Ctypora-user-images%5Cimage-20200617011617003.png)]

[外鏈圖片轉存失敗,源站可能有防盜鏈機制,建議將圖片保存下來直接上傳(img-8bGnOo0s-1592353385157)(C:%5CUsers%5Clenovo%5CAppData%5CRoaming%5CTypora%5Ctypora-user-images%5Cimage-20200617011633247.png)]

法二:explode(split(列名)):

通常是應用在單列有多個數據,將其打散到對應每一行上進行輸出

  • 常與表生成函數結合使用,將函數的輸入和輸出連接

  • OUTER關鍵字:即使output爲空也會生成結果

    select name,work_place,loc from employee lateral view outer explode(split(null,',')) a as loc;
    # a是表別名 ,loc是列別名
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章