键盘人生

After all,tomorrow is another day

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

行列倒置是SqlServer中常用的技巧之一,不同于SqlServer2000用case拼接的方式,SqlServer2005提供pivot和unpivot关键字来实现这一技巧。

一.使用PIVOT进行行列倒置

示例数据库及测试数据

 表RoleCellConvertDemo中的数据如下:

利用pivot将每个季度的利润转换成横向显示:

select id 编号,[name] 姓名,[1] 第一季度,[2] 第二季度,[3] 第三季度,[4] 第四季度
from RowCellConvertDemo
pivot
(
sum(profile) for quarter in([1],[2],[3],[4])
)
as pvt

 结果:

 

 

二.使用unpivot进行反向操作

示例数据库及测试数据

CellRowConvertDemo数据:

利用unpivot进行反向操作

select id,[name],quarter,profile
from CellRowConvertDemo
unpivot
(
profile 
for quarter in([Q1],[Q2],[Q3],[Q4])
)
as unpvt

结果:

posted on 2010-12-10 15:34  Dr.Wang  阅读(4477)  评论(0编辑  收藏  举报