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

一.使用PIVOT进行行列倒置

示例数据库及测试数据

 表RoleCellConvertDemo中的数据如下:

[转]SqlServer行列倒置示例

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

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

 结果:

[转]SqlServer行列倒置示例

 

 

二.使用unpivot进行反向操作

示例数据库及测试数据

CellRowConvertDemo数据:

[转]SqlServer行列倒置示例

利用unpivot进行反向操作

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

结果:

[转]SqlServer行列倒置示例

相关文章:

  • 2021-07-26
  • 2021-08-23
  • 2021-06-14
  • 2022-02-23
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-10-14
  • 2022-12-23
  • 2022-01-27
  • 2022-12-23
  • 2022-02-03
  • 2022-01-06
  • 2021-11-01
相关资源
相似解决方案