2017-02-09 41 views
0

刚学SQL - 我有如下表:行的列 - SQL 2008

Site1 Totals 
Status1 20 
Status2 5 
Status3 15 
Status4 145 
Status5 1 

,需要行和列进行转换,增加一个新的列名“服务器名称”和改变行列,返回以下内容:

Server name Status1 Status2 Status3 Status4 Status5 
Site1   20  5  15  145  1 

有人能帮助吗?

三江源

+0

'PIVOT'做这个。如果存在未知数量的可能的状态值,请在此网站上搜索* dynamic pivot *。 –

+0

Site1和总计您的列标题? – balaji

回答

0
select ServerName = 'Site1', * 
from 
(
    select Totals, Site1 
    from Sometable 
) d 
pivot 
(
    max(Totals) 
    for Site1 in (Status1, Status2, Status3, Status4, Status5) 
) piv; 

编辑
如果您需要动态地加载从站点1列的值,你可以这样来做:

CREATE table #yourtable 
    ([Site1] varchar(20), [Totals] int) 
; 

INSERT INTO #yourtable 
    ([Site1], [Totals]) 
VALUES 
    ('Status1', 20), 
    ('Status2', 45), 
    ('Status3', 77), 
    ('Status4', 55) 
; 


DECLARE @cols AS NVARCHAR(MAX), 
    @query AS NVARCHAR(MAX) 

select @cols = STUFF((SELECT ',' + QUOTENAME(Site1) 
        from #yourtable 
        group by Site1 
      FOR XML PATH(''), TYPE 
      ).value('.', 'NVARCHAR(MAX)') 
     ,1,1,'') 

set @query = N'SELECT ServerName=''Site1'', ' + @cols + N' from 
      (
       select Site1, Totals 
       from #yourtable 
      ) x 
      pivot 
      (
       max(Totals) 
       for Site1 in (' + @cols + N') 
      ) p ' 

exec sp_executesql @query; 

DEMO

+0

完美:)谢谢 – MikeD