2015-10-04 40 views
0

我有下面的表格格式/數據,它們試圖使用SQL Server Pivot語句轉置。儘管谷歌搜索了最後24小時不能得到它。如何在多列上使用SQL Server Pivot

這是我的表:

 
--------- ------  -------  -------  ------- 
Product  Brand  Region1  Region2  Region3 
--------- ------  -------  -------  ------- 
Product A BrandX  120  1005   7500 
Product B BrandY  522  422   566 
Product C BrandX  455  255   655 

這是我想達到的效果:

 
--------- ------  -------  -------  
Product  Product A Product B Product C 
--------- ------  -------  -------  
Brand  BrandX  BrandY  BrandX 
Region1  120   522   455 
Region2  1005  422   255 
Region3  7500  566   655 

感謝您的幫助。

+0

是您想要的輸出中的第一行電子郵件頭?如果是這樣,你可以請標記標題? – DarkKnight

回答

0

只需使用unpivot的樞軸內,記住列轉換爲相同類型:

SELECT * 
FROM 
(
    SELECT * 
    FROM 
    (SELECT Product, Brand, 
     convert(varchar(6), Region1) as Region1, 
     convert(varchar(6), Region2) as Region2, 
     convert(varchar(6), Region3) as Region3 
     FROM Table1) t1 
    UNPIVOT 
    (Data FOR Col IN 
     (Brand, Region1, Region2, Region3) 
)AS unpvt 
) P 
PIVOT 
(
    max (Data) 
    FOR Product IN 
    ([Product A], [Product B], [Product C]) 
) AS pvt 

實例SQL Fiddle

+0

謝謝。下面的Giorgi版本也非常出色。 – ibexy

0

相同,但有一點不同的版本:

;with cte as(select Product, 
        Brand, 
        cast(Region1 as varchar(100)) Region1, 
        cast(Region2 as varchar(100)) Region2,    
        cast(Region3 as varchar(100)) Region3 
      from t)   
select b as Product, [Product A], [Product B], [Product C] 
from cte 
unpivot(a for b in([Brand],[Region1],[Region2],[Region3]))u 
pivot(max(a) for Product in([Product A],[Product B],[Product C]))p 

這裏撥動http://sqlfiddle.com/#!3/c23cfa/3

+0

這也很好。謝謝! – ibexy