SQL Server 中行转列 列转行

行转列:

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
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值