【SqlServer】行列倒置示例

本文介绍如何在SQL Server中使用PIVOT和UNPIVOT关键字进行行列转换。通过具体示例展示如何将纵向数据转为横向数据,并反之亦然。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

行列倒置是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,'a',2,2000)
insert into RoleCellConvertDemo values(1,'a',3,4000)
insert into RoleCellConvertDemo values(1,'a',4,5000)
insert into RoleCellConvertDemo values(2,'b',1,3000)
insert into RoleCellConvertDemo values(2,'b',2,3500)
insert into RoleCellConvertDemo values(2,'b',3,4200)
insert into RoleCellConvertDemo values(2,'b',4,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,'a',1000,2000,4000,5000)
insert into CellRowConvertDemo values(2,'b',3000,3500,4200,5500)

CellRowConvertDemo数据:

利用unpivot进行反向操作

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

结果:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值