有朋友問「如何直接unpivot成2個欄位」,如下所示,
先準備測試資料如下,
14 |
insert into T VALUES ( 'Z01' , '2012' , '1' ,100,-10,200,30,50,60); |
15 |
insert into T VALUES ( 'Z01' , '2012' , '3' ,200,20,100,20,30,40); |
16 |
insert into T VALUES ( 'Z01' , '2013' , '3' ,300,30,10,50,70,30); |
因為原本欄位A01, A02, A03要放到欄位A,B01, B02, B03要放到欄位B,所以需要2個UNPIVOT,如下,
1 |
SELECT no , yearx, z_type, A, B, x1, x2 |
5 |
UNPIVOT ( A FOR x1 IN (A01, A02, A03) ) AS UnA |
6 |
UNPIVOT ( B FOR x2 IN (B01, B02, B03) ) AS UnB |
上面的輸出筆數為27筆,而我們可以發現,x1, x2欄位中,A01 搭配 B01,A02 要搭配 B02,A03 要搭配 B03,如下圖所示,
所以我們需要再加入 關鍵的 WHERE 條件, RIGHT(x1, 1) = RIGHT(x2, 1),就可以過濾出我們所需要的資料,如下,
1 |
SELECT no , yearx, z_type, A, B, x1, x2 |
5 |
UNPIVOT ( A FOR x1 IN (A01, A02, A03) ) AS UnA |
6 |
UNPIVOT ( B FOR x2 IN (B01, B02, B03) ) AS UnB |
7 |
WHERE RIGHT (x1, 1) = RIGHT (x2, 1) |
如果要加上序號的話,就加入 ROW_NUMBER 就可以了,如下,
02 |
, ROW_NUMBER() OVER(PARTITION BY no , yearx, z_type ORDER BY no , yearx, z_type) AS SEQX |
05 |
SELECT no , yearx, z_type, A, B, x1, x2 |
09 |
UNPIVOT ( A FOR x1 IN (A01, A02, A03) ) AS UnA |
10 |
UNPIVOT ( B FOR x2 IN (B01, B02, B03) ) AS UnB |
11 |
WHERE RIGHT (x1, 1) = RIGHT (x2, 1) |