sql server 行列转换

创建测试表

if object_id('tempdb..#Score','U') is not null
    drop table tempdb.#Score
go
create table #Score(name nvarchar(10),course nvarchar(20),score decimal(10,2))
insert into #Score(name,course,score)
values('张三','语文',81),('张三','数学',82),('张三','英语',83)
,('李四','语文',91),('李四','数学',92)

行转列语句

select name,
    max(case when course='语文' then score end) '语文',
    max(case when course='数学' then score end) '数学',
    max(case when course='英语' then score end) '英语'
from #Score 
group by name

行转列,转换前后比较

 

 

列转行语句

select name,'语文' 'course',语文 'score'
from #Score2
union all
select name,'数学' 'course',数学 'score'
from #Score2
union all
select name,'英语' 'course',英语 'score'
from #Score2

列转行,转换前后比较

 

posted @ 2020-12-04 19:58  温故纳新  阅读(194)  评论(0编辑  收藏  举报