SQL SERVER 行转列 - 游标

准备数据

CREATE  TABLE  TestTable
( 
[Id]  [int]  IDENTITY(1 , 1)  NOT  NULL , 
[UserName]  [nvarchar](50)  NULL , 
[Subject]  [nvarchar](50)  NULL , 
[Source]  [numeric](18, 0)  NULL 
) 
ON  [PRIMARY]
GO

INSERT  INTO  TestTable ([UserName] , [Subject] , [Source])  
SELECT  N'张三' , N'语文' , 60 
UNION  ALL 
SELECT  N'李四' , N'数学' , 70 
UNION  ALL 
SELECT  N'王五' , N'英语' , 80 
UNION  ALL 
SELECT  N'王五' , N'数学' , 75 
UNION  ALL 
SELECT  N'王五' , N'语文' , 57 
UNION  ALL 
SELECT  N'李四' , N'语文' , 80 
UNION  ALL 
SELECT  N'张三' , N'英语' , 100
GO

静态行转列

select  UserName  姓名 ,
sum(case  Subject  when  '语文'  then  Source  else  0  end)  语文 ,
sum(case  Subject  when  '数学'  then  Source  else  0  end)  数学 ,
sum(case  Subject  when  '英语'  then  Source  else  0  end)  英语 
from  TestTable 
group  by  UserName

动态行转列

declare  @fusername  varchar(30)
declare  @fsubject  varchar(30)
declare  @fsource  int
declare  @sql  varchar(500)
--1.创建临时表
create  table  #tmp1(姓名  varchar(10))

--2.第一次循环:构建表格动态列
declare  mycursor  cursor  for 
select  [subject]  from  testtable group  by  [subject] 
open  mycursor 
fetch  next  from  mycursor  into  @fsubject
while (@@fetch_status=0) 
begin 
exec('alter  table  #tmp1  add  ['+@fsubject+']  int  not  null  default(0)')
fetch  next  from  mycursor  into  @fsubject
end 
close  mycursor 
DEALLOCATE  mycursor

--select  *  from  #tmp1

--3.插入唯一姓名
insert  into  #tmp1(姓名) 
select  [username]  from  testtable  group  by  [username]

--select  *  from  #tmp1

--4.第二次循环更新数据
declare  mycursor2  cursor  for 
select  username , [subject] , [Source]  from  testtable
open  mycursor2 
fetch  next  from  mycursor2  into  @fusername , @fsubject , @fsource
while (@@fetch_status=0) 
begin 
set  @sql= 'update  t1  set  ['+@fsubject+'] = '+convert(varchar(10) , @fsource)+'  from  #tmp1  t1  where  姓名='''+@fusername+'''  '
print  @sql
exec(@sql)
fetch  next  from  mycursor2  into  @fusername , @fsubject , @fsource
end 
close  mycursor2 
DEALLOCATE  mycursor2

select  *  from  #tmp1

truncate  table  #tmp1
drop  table  #tmp1

使用pivot行转列

select  * 
from
(
	select  UserName , [Subject] , [Source]  from  TestTable
)  test 
pivot 
(
	sum(Source)  for  Subject  in (语文 , 数学 , 英语)
)  pvt
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值