如何在多个列上使用 SQL Server Pivot
How to use SQL Server Pivot on Multiple columns
我有以下 table 格式/数据,它们正在尝试使用 SQL Server Pivot 语句进行转置。尽管谷歌搜索了最后 24 小时,还是无法得到它。
这是我在 table:
--------- ------ ------- ------- -------
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
感谢您的帮助。
只需在数据透视表中使用 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
中的例子
相同,但版本略有不同:
;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
我有以下 table 格式/数据,它们正在尝试使用 SQL Server Pivot 语句进行转置。尽管谷歌搜索了最后 24 小时,还是无法得到它。
这是我在 table:
--------- ------ ------- ------- ------- 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
感谢您的帮助。
只需在数据透视表中使用 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
中的例子
相同,但版本略有不同:
;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