在 sql 服务器中将行转换为列?
Convert rows to columns in sql server?
我正在寻找一种在 SQL 服务器中将行转换为列的有效方法,我听说 PIVOT 是我正在寻找的,我是数据透视表的新手。
这是我的例子:
ItemID VendorName VendorPrice
122 HP 125.66
122 Apple 130.44
122 Microsoft 134.00
122 IBM 124.90
这是我的预期结果:
ItemID HPPrice ApplePrice MicrosoftPrice IBMPrice
122 125.66 130.44 134.00 124.90
如何使用数据透视表构建结果?
declare @table table (Itemid Int,Vendorname varchar(10),VendorPrice DECIMAL(18,2))
insert into @table (Itemid,Vendorname,VendorPrice)
values (122,'HP',125.66),
(122,'Apple',130.44),
(122,'microsoft',134.00),
(122,'IBM',124.90)
Select Itemid,[HP] As HPPrice ,
[Apple] As ApplePrice,
[microsoft] As microsoftPrice,
[IBM] As IBMPrice from (
select Itemid,Vendorname,VendorPrice from @table)A
PIVOT(MAX(VendorPrice) FOR Vendorname IN ([HP],[Apple],[microsoft],[IBM]))P
我正在寻找一种在 SQL 服务器中将行转换为列的有效方法,我听说 PIVOT 是我正在寻找的,我是数据透视表的新手。
这是我的例子:
ItemID VendorName VendorPrice
122 HP 125.66
122 Apple 130.44
122 Microsoft 134.00
122 IBM 124.90
这是我的预期结果:
ItemID HPPrice ApplePrice MicrosoftPrice IBMPrice
122 125.66 130.44 134.00 124.90
如何使用数据透视表构建结果?
declare @table table (Itemid Int,Vendorname varchar(10),VendorPrice DECIMAL(18,2))
insert into @table (Itemid,Vendorname,VendorPrice)
values (122,'HP',125.66),
(122,'Apple',130.44),
(122,'microsoft',134.00),
(122,'IBM',124.90)
Select Itemid,[HP] As HPPrice ,
[Apple] As ApplePrice,
[microsoft] As microsoftPrice,
[IBM] As IBMPrice from (
select Itemid,Vendorname,VendorPrice from @table)A
PIVOT(MAX(VendorPrice) FOR Vendorname IN ([HP],[Apple],[microsoft],[IBM]))P