微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

【SqlServer】行列倒置示例

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

一.使用PIVOT进行行列倒置

create table RoleCellConvertDemo(id int,name varchar(20),quarter int,profile int)
insert into RoleCellConvertDemo values(1,'a',1,1000)
insert into RoleCellConvertDemo values(1,2,2000)
insert into RoleCellConvertDemo values(1,3,4000)
insert into RoleCellConvertDemo values(1,4,5000)
insert into RoleCellConvertDemo values(2,'b',3000)
insert into RoleCellConvertDemo values(2,3500)
insert into RoleCellConvertDemo values(2,4200)
insert into RoleCellConvertDemo values(2,5500)

表RoleCellConvertDemo中的数据如下:

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

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

结果:

二.使用unpivot进行反向操作

create table CellRowConvertDemo(id int,name varchar(50),Q1 int,Q2 int,Q3 int,Q4 int)
insert into CellRowConvertDemo values(1,1000,2000,4000,5000)
insert into CellRowConvertDemo values(2,3000,3500,4200,5500)

CellRowConvertDemo数据:

利用unpivot进行反向操作

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

结果:

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐