PIVOT 通过将表达式某一列中的唯一值转换为输出中的多个列来旋转表值表达式,并在必要时对最终输出中所需的任何其余列值执行聚合。UNPIVOT 与 PIVOT 执行相反的操作,将表值表达式的列转换为列值。
测试用的数据及表结构:
1. CREATE TABLE ShoppingCart(
2. [Week] INT NOT NULL,
3. [TotalPrice] DECIMAL DEFAULT(0) NOT NULL
4. )
5. INSERT INTO ShoppingCart([Week],[TotalPrice])
6. SELECT 1,10 UNION ALL
7. SELECT 2,20 UNION ALL
8. SELECT 3,30 UNION ALL
9. SELECT 4,40 UNION ALL
10. SELECT 5,50 UNION ALL
11. SELECT 6,60 UNION ALL
12. SELECT 7,70
13. SELECT * FROM ShoppingCart
输出结果:
来看下PIVOT怎么把行变列:
1. SELECT 'TotalPrice' AS [Week],[1],[2],[3],[4],[5],[6],[7]
2. FROM ShoppingCart PIVOT(SUM(TotalPrice) FOR [Week] IN([1],[2],[3],[4],[5],[6],[7])) AS T
输出结果:
可以看出来,转换完成了,就这么个功能。再看一个UNPIVOT函数,与上述功能相反,把列转成行。我们直接使用WITH关键字把上述PIVOT查询当成源表,然后再使用UNPIVOT关键把它旋转回原来的模样,SQL脚本及结果如下:
1. WITH P AS (
2. SELECT 'TotalPrice' AS [Week],[1],[2],[3],[4],[5],[6],[7]
3. FROM ShoppingCart PIVOT(SUM(TotalPrice) FOR [Week] IN([1],[2],[3],[4],[5],[6],[7]))
4. AS T
5. )
6. SELECT
7. [WeekDay] AS [Week],
8. [WeekPrice] AS [TotalPrice]
9. FROM P
10. UNPIVOT(
11. [WeekPrice] FOR [WeekDay] IN([1],[2],[3],[4],[5],[6],[7])
12. )AS FOO