[英]Need to transform pivot table into another format
我想找到某種方法將數據透視表改回普通表。
表1具有以下格式:
acct type Hr08_C Hr09_C Hr10_C Hr08_H Hr09_H Hr10_H
1 1 2 3 4 5 6 7
表2具有以下格式:
acct type hour phone value
1 1 8 C 2
1 1 9 C 3
1 1 10 C 3
1 1 8 H 5
1 1 9 H 6
1 1 10 H 7
我想將表1更改為表2格式。 對查詢有任何想法嗎?
首先執行UNPIVOT
,然后解碼列名稱:
declare @t table (acct int,type int, Hr08_C int, Hr09_C int, Hr10_C int,
Hr08_H int, Hr09_H int, Hr10_H int)
insert into @t (acct,type,Hr08_C,Hr09_C,Hr10_C,Hr08_H,Hr09_H,Hr10_H) values
( 1,1,2,3,4,5,6,7)
select
acct,type,CONVERT(int,SUBSTRING(Encoded,3,2)) as hour,
SUBSTRING(Encoded,6,1) as phone,value
from @t
unpivot (value for Encoded in (Hr08_C,Hr09_C,Hr10_C,Hr08_H,Hr09_H,Hr10_H)) t
結果:
acct type hour phone value
----------- ----------- ----------- ----- -----------
1 1 8 C 2
1 1 9 C 3
1 1 10 C 4
1 1 8 H 5
1 1 9 H 6
1 1 10 H 7
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.