表
ProductID | OrderMonth | SubTotal |
1 | 5 | 100.00 |
1 | 6 | 100.00 |
2 | 5 | 200.00 |
2 | 6 | 200.00 |
2 | 7 | 300.00 |
3 | 5 | 400.00 |
3 | 5 | 400.00 |
SELECT ProductID, [5] AS 五月, [6] AS 六月, [7] AS 七月 FROM Sales.Orders PIVOT ( SUM (Orders.SubTotal) FOR Orders.OrderMonth IN ( [5], [6], [7] ) ) AS pvt ORDER BY ProductID; |
把列轉成行用UNPIVOT,用處不大吧
CREATE TABLE MyPvt (ProductID int, 五月int, 六月 int, 七月int); --建立MyPvt表
GO
--将表5-5中所示的值插入到MyPvt表中
INSERT INTO MyPvt VALUES (1,100,100,0);
INSERT INTO MyPvt VALUES (2,200,200,200);
INSERT INTO MyPvt VALUES (3,800,0,0);
--执行UNPIVOT
SELECT ProductID, OrderMonth, SubTotal
FROM
MyPvt UNPIVOT
(SubTotal FOR OrderMonth IN
(五月, 六月, 七月)
)AS unpvt;