【问题标题】:Need to transform pivot table into another format需要将数据透视表转换为另一种格式
【发布时间】:2014-05-01 14:31:59
【问题描述】:

我想找到一些方法将数据透视表改回普通表。

表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 格式。请对查询有任何想法?

【问题讨论】:

    标签: sql sql-server pivot pivot-table


    【解决方案1】:

    首先执行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
    

    【讨论】:

    • 那行得通。永远不知道 unpivot 函数。非常感谢!!
    猜你喜欢
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 2012-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多