前面几个例子:
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()可以很轻易实现这些功能。参考下面代码:
View Code
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;
执行结果:
另一种是想把上面的结果进行列行转换:
View Code
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;
执行结果: