如何在多列上使用SQL Server Pivot

时间:2015-10-04 08:18:38

标签: sql-server pivot unpivot

我有使用SQL Server Pivot语句尝试转置的下表格式/数据。尽管谷歌搜索过去24小时仍然无法获得它。

这就是我在表格中的内容:

---------   ------      -------     -------     -------
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

感谢您的帮助。

2 个答案:

答案 0 :(得分: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

中的示例

答案 1 :(得分: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