简体   繁体   English

需要将数据透视表转换为另一种格式

[英]Need to transform pivot table into another format

I want to find some way to change the pivot table back to normal table. 我想找到某种方法将数据透视表改回普通表。

Table 1 has following format: 表1具有以下格式:

acct type Hr08_C Hr09_C Hr10_C Hr08_H Hr09_H Hr10_H
 1    1     2      3      4      5      6       7

Table 2 has following format: 表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

I want to change the table 1 to table 2 format. 我想将表1更改为表2格式。 Any idea about the query, please? 对查询有任何想法吗?

First do the UNPIVOT , then decode the column names: 首先执行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

Result: 结果:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM