首页 > 代码库 > T-SQL PIVOT 行列转换
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()可以很轻易实现这些功能。参考下面代码:
SELECT [RId],[2011-01-23],[2011-01-24],[2011-01-25],[2011-01-26]
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 [DT] IN ([2011-01-23],[2011-01-24],[2011-01-25],[2011-01-26])
) AS Q;
执行结果:
另一种是想把上面的结果进行列行转换:
SELECT [DT],[R1],[R2],[R3],[R4]
FROM
(
SELECT [Rid],[DT],[Hits] FROM [dbo].[RecordHits]
) AS p
PIVOT
(
SUM([Hits]) FOR [RId] IN ([R1],[R2],[R3],[R4])
) AS Q;
FROM
(
SELECT [Rid],[DT],[Hits] FROM [dbo].[RecordHits]
) AS p
PIVOT
(
SUM([Hits]) FOR [RId] IN ([R1],[R2],[R3],[R4])
) AS Q;
执行结果:
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。