我不能将一列转换为多列,也不能将多列转换为行。
解释自己的最好方法是在桌子上
答案 0 :(得分:2)
您可以在SQL Server中使用UNPIVOT
和PIVOT
函数来转置行和列,以下查询应做您想要的事情:
CREATE TABLE #temp (Category VARCHAR(10), [% SKU] INT, [% Aveg Inv] INT, [% Inv Val] INT, [% Shipped Cases] INT, [% Inv Cub] INT, [% Sales] INT)
INSERT INTO #temp VALUES
('Type1',10,4,4,14,0,7),
('Type2',82,30,30,30,0,68),
('Type3',3,1,1,0,0,0),
('Type4',6,65,65,56,0,24)
SELECT pvt.* FROM
(
SELECT [Category], [Value], [Driver]
FROM #temp t
UNPIVOT (Value FOR Driver IN ([% SKU],[% Aveg Inv],[% Inv Val],[% Shipped Cases],[% Inv Cub],[% Sales])) a) unpvt
PIVOT (SUM([Value]) FOR [Category] IN ([Type1],[Type2],[Type3],[Type4])) pvt
ORDER BY CASE Driver
WHEN '% SKU' THEN 1
WHEN '% Aveg Inv' THEN 2
WHEN '% Inv Val' THEN 3
WHEN '% Shipped Cases' THEN 4
WHEN '% Inv Cub' THEN 5
WHEN '% Sales' THEN 6 END
结果如下,
Driver Type1 Type2 Type3 Type4
% Aveg Inv 4 30 1 65
% Inv Cub 0 0 0 0
% Inv Val 4 30 1 65
% Sales 7 68 0 24
% Shipped Cases 14 30 0 56
% SKU 10 82 3 6