SQL Server 中行转列 列转行

本文介绍使用SQL进行数据转换的方法,包括利用CASE WHEN语句和PIVOT函数实现行转列,以及使用UNPIVOT操作实现列转行。这些技术对于处理复杂的数据格式非常有用。

行转列:

Create database Test
on primary (
    name='Test.mdf',
    fileName='D:\\project\Test.mdf',
    size=10mb,
    fileGrowth=15%
)
log on(
    name='Test.ndf',
    fileName='D:\\project\Test.ldf',
    size=3mb,
    fileGrowth=15%
)
go
use Test
go
create table Score(
    ID int primary key identity(1,1),
    name varchar(20) not null,
    course varchar(5),
    scores numeric(5,0)
)
go
drop table Score

insert into Score
Select '张三','语文',90.2union
Select '张三','数学',85.7union
Select '张三','英语',75union
Select '李四','语文',55union
Select '李四','英语',40union
Select '李四','数学',59union
select '王五','语文',60union
select '王五','数学',70union
select '王五','英语',30


1.通过Case  where  条件1 then  结果1     多分支语句

select name as 姓名,SUM(case when course='语文' then scores else 0 end) as 语文成绩
,SUM(case when course='数学' then scores else 0 end) as 数学成绩
,SUM(case when course='英语' then scores else 0 end) as 英语成绩
 from Score group by name


2.通过pivot

select * from Score
 pivot(max(scores) for course in(语文,数学,英语)) b


列转行:

1.UNPIVOT

CREATE TABLE pvt (VendorID int, Emp1 int, Emp2 int,
    Emp3 int, Emp4 int, Emp5 int);
GO
INSERT INTO pvt VALUES (1,4,3,5,4,4);
INSERT INTO pvt VALUES (2,4,1,5,5,5);
INSERT INTO pvt VALUES (3,4,3,5,4,4);
INSERT INTO pvt VALUES (4,4,2,5,5,4);
INSERT INTO pvt VALUES (5,5,1,5,5,5);
GO
--Unpivot the table.
SELECT VendorID, Employee, Orders
FROM
   (SELECT VendorID, Emp1, Emp2, Emp3, Emp4, Emp5
   FROM pvt) p
UNPIVOT
   (Orders FOR Employee IN
      (Emp1, Emp2, Emp3, Emp4, Emp5)
)AS unpvt;
GO

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小DuDu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值