您可以使用
pivot
具有
cross apply
:
declare @tmp table (Year int, Item_Category nvarchar(100), Dollar_Volume int,
No_of_Sales int, [$0-$99] int, [$100-$199] int, [$200-$299] int)
insert into @tmp values
(2018 , 'Produce' , 2359, 23 , 13, 4, 6),
(2018 , 'Clothing' , 4325, 118, 21, 70, 27),
(2018 , 'Fruits' , 3756, 19 , 15, 3, 1),
(2018 , 'Vegetables' , 9124, 64 , 19, 0, 45),
(2018 , 'Packed Food' , 1174, 91 , 7, 67, 17),
(2018 , 'Detergent' , 568, 103, 99, 4, 0),
(2018 , 'Entertainment', 6127, 925, 32, 500, 393)
select piv.Year, piv.COL as [Column], piv.Produce, piv.Clothing, piv.Fruits,
piv.Vegetables, piv.[Packed Food], piv.Detergent, piv.Entertainment
from
(
select [Item_Category] , COL,VAL, [YEAR], ORD
from @tmp
CROSS APPLY (VALUES
('Dollar_Volume',[Dollar_Volume],1),
('No_of_Sales' ,[No_of_Sales] ,2),
('$0-$99' ,[$0-$99] ,3),
('$100-$199' ,[$100-$199] ,4),
('$200-$299' ,[$200-$299] ,5)
)CS (COL,VAL,ORD)
) src
pivot ( max(val) for [Item_Category] in ([Produce], [Clothing], [Fruits], [Vegetables],
[Packed Food], [Detergent], [Entertainment]) ) piv
order by piv.ORD
结果: