如何排列数据透视表的列

时间:2015-02-23 16:02:03

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

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

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%

2 个答案:

答案 0 :(得分:3)

如果您只有这两个值,请尝试使用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关于“联盟所有”的建议

答案 1 :(得分:0)

可能需要unpivot而不是转动。我将使用cross applytables valued constructor进行此操作。

如果你有更多的Union All

,那么性能明智优于names
SELECT [date],NAME, uptime, downtime
FROM   Yourtable
       CROSS apply (VALUES ('service',Services_Uptime,Services_Downtime),
                           ('center',Centers_Uptime,Centers_Downtime) ) 
                    cs (NAME, uptime, downtime)