Sql Server 行转列的多种写法

if not object_id('Class') is null
drop table Class
Go
Create table Class([Student] nvarchar(2),[Course] nvarchar(2),[Score] int)
Insert Class
select N'张三',N'语文',78 union all
select N'张三',N'数学',87 union all
select N'张三',N'英语',82 union all
select N'张三',N'物理',90 union all
select N'李四',N'语文',65 union all
select N'李四',N'数学',77 union all
select N'李四',N'英语',65 union all
select N'李四',N'物理',85
Go
select * from class
GO

/*******************************************
 *  第一种写法
 *	用静态脚本 
 *******************************************/

select
student
--通过Case When 实现行转列功能
,max(case [Course] when '数学' then Score else 0 end) as [数学]
,max(case [Course] when '物理' then Score else 0 end) as [物理]
,max(case [Course] when '英语' then Score else 0 end) as [英语]
,max(case [Course] when '语文' then Score else 0 end) as [语文]
,sum(Score) as sum_socre
,avg(Score) as avg_Score
from class
group by student
Go
/*******************************************
 *	第二种写法
 *	动态脚本,行转列。 
 *******************************************/
declare @sql nvarchar(max);
declare @i int;
set @sql = ''
set @i = 1
select @sql = @sql + 
			  ',max(case when [Course]=''' + 
			  [Course] +'''' +
			  ' then [Score]  end) as '+[Course]+'',
	   @i = @i + 1
from class  
group by [Course]

set @sql = 'select [Student]' + @sql + ' from class
group by [Student]'

exec(@sql)


/*******************************************
 * 第三种写法:
 * 用Pivot静态脚本,通过Pivot功能实现行转列
	语法:
	table_source
	PIVOT(
	聚合函数(value_column)
	FOR pivot_column
	IN(<column_list>)
 *******************************************/
select
Student,
[语文],
[数学],
[英语],
[物理]
from Class
pivot
(
max(Score) for Course in([语文],[数学],[英语],[物理])
)T
GO
/*******************************************
 * 第四种写法:
 * pivot 动态脚本
 *******************************************/
declare @sql varchar(max)
select @sql=ISNULL(@sql+',','')+quotename(Course)
from Class
group by Course

exec
('
select * from Class
pivot
(
max(Score) for Course in ('+@sql+')
)T'
)
go

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值