行列倒置是SqlServer中常用的技巧之一,不同于SqlServer2000用case拼接的方式,SqlServer2005提供pivot和unpivot关键字来实现这一技巧。
一.使用PIVOT进行行列倒置
示例数据库及测试数据 表RoleCellConvertDemo中的数据如下:
![](https://images.cnblogs.com/cnblogs_com/hongtao/data.jpg)
利用pivot将每个季度的利润转换成横向显示:
select id 编号,[name] 姓名,[1] 第一季度,[2] 第二季度,[3] 第三季度,[4] 第四季度
from RowCellConvertDemo
pivot
(
sum(profile) for quarter in([1],[2],[3],[4])
)as pvt
结果:
![](https://images.cnblogs.com/cnblogs_com/hongtao/Result.jpg)
二.使用unpivot进行反向操作
示例数据库及测试数据CellRowConvertDemo数据:
![](https://images.cnblogs.com/cnblogs_com/hongtao/Result.jpg)
利用unpivot进行反向操作
select id,[name],quarter,profile
from CellRowConvertDemo
unpivot
(
profile for quarter in([Q1],[Q2],[Q3],[Q4])
)as unpvt
结果:
![](https://images.cnblogs.com/cnblogs_com/hongtao/data.jpg)