62,249
社区成员
发帖
与我相关
我的任务
分享

--建立测试环境
set nocount on
create table testRecord(id int,userid int,classid int,classvalue int)
insert into testRecord select '1','2','1','80'
insert into testRecord select '2','3','1','70'
insert into testRecord select '3','4','1','60'
insert into testRecord select '4','2','2','50'
insert into testRecord select '5','3','2','40'
insert into testRecord select '6','4','2','30'
insert into testRecord select '7','2','3','20'
insert into testRecord select '8','3','3','10'
insert into testRecord select '9','4','3','90'
go
create table testUser(id int,name varchar(10))
insert into testUser select 2,'张三'
insert into testUser select 3,'李四'
insert into testUser select 4,'王五'
create table testClass(id int,classname varchar(10))
insert into testClass select 1,'语文'
insert into testClass select 2,'数学'
insert into testClass select 3,'英语'
--测试
select name
,max(case when classid=1 then classvalue else 0 end)语文
,max(case when classid=1 then rank else 0 end)排名
,max(case when classid=2 then classvalue else 0 end)数学
,max(case when classid=2 then rank else 0 end)排名
,max(case when classid=3 then classvalue else 0 end)英语
,max(case when classid=3 then rank else 0 end)排名
from(
select *,rank=RANK()over(partition by classname order by classvalue desc) from(
select a.userid,b.name,a.classid,c.classname,a.classvalue
from testRecord a,testUser b,testClass c
where a.userid=b.id and a.classid=c.id
)a)b
group by name,userid order by userid
--删除测试环境
drop table testRecord
drop table testUser
drop table testClass
set nocount off
/*
name 语文 排名 数学 排名 英语 排名
---------- ----------- -------------------- ----------- -------------------- ----------- --------------------
张三 80 1 50 1 20 2
李四 70 2 40 2 10 3
王五 60 3 30 3 90 1
*/