Hive典型應用場景之行列轉換

2021-08-07 13:30:30 字數 2851 閱讀 7319

在使用hive處理資料時,經常遇到行列轉換的場景,本文將對hive的行列轉換操作做詳細的說明。

1)多行轉多列

假設資料表

row2col:

col1   col2    col3

a c 1

a d 2

a e 3

b c 4

b d 5

b e 6

現在要將其轉化為:

col1   c      d      e

a 1 2 3

b 4 5 6

此時需要使用到max(case … when … then … else 0 end),僅限於轉化的字段為數值型別,且為正值的情況。

hql語句為:

select col1,

max(case col2 when 'c' then col3 else 0 end) as c,

max(case col2 when 'd' then col3 else 0 end) as d,

max(case col2 when 'e' then col3 else 0 end) as e

from row2col

group by col1;

2)多行轉單列

假設資料表

row2col:

col1    col2    col3

a b 1

a b 2

a b 3

c d 4

c d 5

c d 6

現在要將其轉化為:

col1    col2    col3

a b 1,2,3

c d 4,5,6

此時需要用到兩個內建的udf:

a)cocat_ws(引數1,引數2),用於進行字元的拼接

引數1—指定分隔符

引數2—拼接的內容

b)collect_set(),它的主要作用是將某字段的值進行去重彙總,產生array型別字段。

hql語句為:

select col1, col2, concat_ws(',', collect_set(col3)) as col3

from row2col

group by col1, col2;

注意:由於使用concat_ws()函式,collect_set()中的字段必須為string型別,如果是其他型別可使用cast(col3 as string)將其轉換為string型別。

1)多列轉多行

假設有資料表

col2row:

col1   c      d      e

a 1 2 3

b 4 5 6

現要將其轉化為:

col1   col2    col3

a c 1

a d 2

a e 3

b c 4

b d 5

b e 6

這裡需要使用union進行拼接。

hql語句為:

select col1, 'c' as col2, c as col3 from col2row

union all

select col1, 'd' as col2, d as col3 from col2row

union all

select col1, 'e' as col2, e as col3 from col2row

order by col1, col2;

2)單列轉多行

假設有資料表

col2row:

col1    col2    col3

a b 1,2,3

c d 4,5,6

現要將其轉化為:

col1    col2    col3

a b 1

a b 2

a b 3

c d 4

c d 5

c d 6

這裡需要使用udtf(表生成函式)explode(),該函式接受array型別的引數,其作用恰好與collect_set相反,實現將array型別資料行轉列。explode配合lateral view實現將某列資料拆分成多行。

hql語句為:

select col1, col2, lv.col3 as col3

from col2row

lateral view explode(split(col3, ',')) lv as col3;

hive使用適用場景 hive的典型應用場景

案例一 需求 現有這麼一批資料,現要求出 每個使用者截止到每月為止的最大單月訪問次數和累計到該月的總訪問次數。資料 使用者名稱,月份,訪問次數 a,2015 01,5 a,2015 01,15 b,2015 01,5 a,2015 01,8 b,2015 01,25 a,2015 01,5 a,20...

ZooKeeper典型應用場景

zookeeper 是乙個開源的高可用的分布式資料管理與系統協調框架,基於對 paxos 演算法的實現,保證了分布式環境中資料的強一致性。發布與訂閱模型 發布者發布資料到 zk 節點上,供訂閱者動態獲取資料。在資料量很少,但是資料更新快的場景下 訊息中介軟體中的發布者和訂閱者的負載均衡,linked...

SSIS典型應用場景分析

ssis 提供一系列支援業務應用程式開發的內建任務 容器 轉換和資料介面卡,方便我們建立解決方案來解決複雜的業務問題,除了可以管理 sql server 資料庫以及在 sql server 例項之間複製 sql server 物件,我們還可以對oracle mysql excel等不同的異構資料來源...