SQL行列互换很方便

女爷i 2022-10-02 06:53 271阅读 0赞

-—行转列—pivot
create table tempTable
(
id int primary key identity(1,1),
Student nvarchar(36),
[Subject] nvarchar(36),
Score int,
)

select * from tempTable
insert into tempTable values (‘张三’,’语文’,’90’)
insert into tempTable values (‘张三’,’语文’,’89’)
insert into tempTable values (‘李四’,’语文’,’90’)
insert into tempTable values (‘王五’,’语文’,’93’)
insert into tempTable values (‘张三’,’数学’,’89’)
insert into tempTable values (‘李四’,’数学’,’79’)
insert into tempTable values (‘王五’,’数学’,’88’)
insert into tempTable values (‘张三’,’英语’,’87’)
insert into tempTable values (‘李四’,’英语’,’94’)
insert into tempTable values (‘王五’,’英语’,’96’)

select Student,sum(语文)as 语文,sum(数学) as 数学,sum(英语) as 英语 into tempsubject from tempTable pivot(avg(Score) for [Subject] in (语文,数学,英语)) as A group by Student order by 语文 desc

-—列转行unpivot
select * from tempsubject
unpivot
(
Score for [Subject] in(语文,数学,英语)
)
as f

转载于:https://blog.51cto.com/5090844/1615243

发表评论

表情:
评论列表 (有 0 条评论,271人围观)

还没有评论,来说两句吧...

相关阅读

    相关 SQL面试题(行列互换

    有一个SQL面试题(行列互换)在面试中出现的概率极高,最近有学生出去面试仍然会遇到这样的题目,在这里跟大家分享一下。 题目:数据库中有一张如下所示的表,表名为sales。