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
Sql Server 行转列的多种写法
最新推荐文章于 2024-07-23 15:38:58 发布