【问题标题】:How to line up columns of a pivot table如何排列数据透视表的列
【发布时间】:2015-02-23 16:02:03
【问题描述】:

我有一个像这样创建的数据透视表:

date    Services Uptime     Services Downtime   Centers Downtime Centers Uptime
-----   --------- -     ------------------    ----------------    ---------------
12/5/14      100.00%              0.00%                   100.00%        100.00%    
12/12/14     100.00%              0.00%                     0.00%          0.00%
12/19/14     100.00%              0.00%                   100.00%        0.00%
12/26/14     100.00%              0.00%                   100.00%         0.00%

我希望它以数据透视表的形式出现,如下所示:

Date         Name                Uptime               Downtime
-----        ------            ---------            -------------
12/5/14     Services             100.00%                 0.00%  
12/5/14      Center              100.00%               100.00%
12/12/14    services             100.00%                 0.00%  
12/12/14    Center                 0.00%                 0.00%

【问题讨论】:

    标签: sql sql-server database pivot pivot-table


    【解决方案1】:

    如果您只有这两个值,请尝试 UNION:

    select  [date]
            ,'Services'
            ,[Services Uptime] as Uptime
            ,[Services Dowtime] as Downtime
    from    myTable
    union all
    select  [date]
            ,'Center'
            ,[Centers Uptime] as Uptime
            ,[Centers Dowtime] as Downtime
    from    myTable
    

    已编辑:包括 Jason 关于“联合all”的建议

    【讨论】:

    • 虽然这并没有错,但使用 union all 而不是 union 可以(取决于表、索引等)在这种情况下显着提高性能(您不会有任何重复行,反正)。
    • 谢谢伙计,但我有超过 6 个这样的值。你能请。建议我一个最好的方法。
    【解决方案2】:

    您可能需要unpivot 而不是旋转。我将使用cross applytables valued constructor 来做到这一点。

    性能方面,如果您有更多 names,这将比 Union All 更好

    SELECT [date],NAME, uptime, downtime
    FROM   Yourtable
           CROSS apply (VALUES ('service',Services_Uptime,Services_Downtime),
                               ('center',Centers_Uptime,Centers_Downtime) ) 
                        cs (NAME, uptime, downtime) 
    

    【讨论】:

    • 感谢您提供更好的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-06
    • 2020-06-18
    • 2016-04-10
    • 2021-02-03
    • 2020-05-05
    相关资源
    最近更新 更多