2013-08-19 61 views

回答

2

好吧,在仔細查看你的問題後,我認爲這不是重複的,你不僅要將列轉換爲行,還要將行同時轉換爲列。
所以,你有兩個解決方案結合 - unpivoting列行和樞行列,是這樣的:

select 
    c.name as ColX, 
    max(case when t.id = 1 then c.value else null end) as [1], 
    max(case when t.id = 2 then c.value else null end) as [2] 
from Table1 as t 
    cross apply (values 
     ('AA', t.AA), 
     ('BB', t.BB), 
     ('CC', t.CC), 
     ('DD', t.EE) 
    ) as c(name, value) 
group by c.name 

sql fiddle demo

你也可以使用standard pivot and unpivot從SQL Server:

select * 
from Table1 as t 
unpivot (
    value for 
    colx in (AA, BB, CC, DD, EE, FF) 
) as unpiv 
pivot (
    max(unpiv.value) 
    for id in ([1], [2]) 
) as piv 

sql fiddle demo

如果你不想指定VA ID和列的梅毒,嘗試動態SQL:

declare @stmt1 nvarchar(max), @stmt2 nvarchar(max), @stmt nvarchar(max) 

select @stmt1 = 
    isnull(@stmt1 + ', ', '') + 
    '(''' + c.column_name + ''', t.' + c.column_name + ')' 
from information_schema.columns as c 
where c.table_name = 'Table1' and c.column_name <> 'id' 

select @stmt2 = 
    isnull(@stmt2 + ', ', '') + 'max(case when t.id = ' + t.id + ' then c.value end) as [' + t.id + ']' 
from (select distinct cast(id as nvarchar(max)) as id from Table1) as t 

select @stmt = ' 
    select 
     c.name as ColX, ' + @stmt2 + ' 
    from Table1 as t 
     cross apply (values ' + @stmt1 + ') as c(name, value) 
    group by c.name' 

exec sp_executesql @stmt = @stmt 

sql fiddle demo

+0

謝謝羅馬PEKAR, 但ID不能修復,請再幫。 – user2695757

+0

查看更新的答案 –

+0

好的解決方案,非常感謝。 – user2695757