一、需求
需要將多行的資料,按照某個維度轉換為一行。
轉換前:
轉換後:
db_price : area_name 為 東北 的total_price_actual;
db_qty : area_name 為 東北 的qty。
二、解決方案:
1、sql
select brand,
max(case when area_name='東北' then total_price_actual else 0 end) db_price,
max(case when area_name='華北' then total_price_actual else 0 end) hb_price,
max(case when area_name='華東' then total_price_actual else 0 end) hd_price,
max(case when area_name='華南' then total_price_actual else 0 end) hn_price,
max(case when area_name='西南' then total_price_actual else 0 end) xn_price,
max(case when area_name='西北' then total_price_actual else 0 end) xb_price,
max(case when area_name='東北' then qty else 0 end) db_qty,
max(case when area_name='華北' then qty else 0 end) hb_qty,
max(case when area_name='華東' then qty else 0 end) hd_qty,
max(case when area_name='華南' then qty else 0 end) hn_qty,
max(case when area_name='西南' then qty else 0 end) xn_qty,
max(case when area_name='西北' then qty else 0 end) xb_qty
from (
select brand, area_name, sum(total_price_actual) total_price_actual, sum(qty) qty
from hive_temp_vipvop.vop_xstore_retail
group by brand, area_name
) tmp
group by brand
2、sql
select brand,
kv1['華北'] hb_price, kv2['華北'] hb_qty,
kv1['華東'] hd_price, kv2['華東'] hd_qty,
kv1['東北'] db_price, kv2['東北'] db_qty,
kv1['華南'] hn_price, kv2['華南'] hn_qty,
kv1['西南'] sn_price, kv2['西南'] xn_qty,
kv1['西北'] xb_price, kv2['西北'] xb_qty
from (
select brand, str_to_map(concat_ws(',', collect_set(concat(area_name, '-', total_price_actual))),',','-') kv1,
str_to_map(concat_ws(',', collect_set(concat(area_name, '-', qty))),',','-') kv2
from (
select brand, area_name, sum(total_price_actual) total_price_actual, sum(qty) qty
from hive_temp_vipvop.vop_xstore_retail
group by brand, area_name
) tmp
group by brand
) t
SQL SERVER 多行轉多列
轉換結果如上圖 建立測試標 create table 成績表 編號 int identity 1,1 not null,姓名 varchar 50 null,語文 numeric 5,2 null,數學 numeric 5,2 null,英語 numeric 5,2 null on primary ...
行列轉換之 多行轉多列,多列轉多行實踐版
行列轉換之 多行轉多列,多列轉多行實踐版 參考 深入行列轉換 多行轉多列,多行的計算 參考 sql server動態行列轉換 要求 實操演示 1.全表 select from temp2 2.構造row number select row number over partition by a ord...
oracle多行轉單行多列
需求 從a轉成b 需要用到以下函式 wm concat 多行轉成一列 case when then else end regexp substr sql如下 select material code,store id,case when regexp substr wm concat shippin...