T-SQL PIVOT 行列转换
前面几个例子:
http://www.cnblogs.com/insus/articles/1969896.html
http://www.cnblogs.com/insus/articles/1970577.html
http://www.cnblogs.com/insus/articles/1970707.html
全是SQL Server行列转换或是列行转换的相关例子。不过在SQL Server2005版本开始,有一个新的函数PIVOT()可以很轻易实现这些功能。参考下面代码:
FROM
(
SELECT [Rid],[DT],[Hits] FROM [dbo].[RecordHits]
) AS p
PIVOT
(
SUM([Hits]) FOR [DT] IN ([2011-01-23],[2011-01-24],[2011-01-25],[2011-01-26])
) AS Q;
执行结果:
另一种是想把上面的结果进行列行转换:
FROM
(
SELECT [Rid],[DT],[Hits] FROM [dbo].[RecordHits]
) AS p
PIVOT
(
SUM([Hits]) FOR [RId] IN ([R1],[R2],[R3],[R4])
) AS Q;
执行结果:
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。