create table cjb(学号 char (10),课程名 char (10),成绩 [decimal](12, 2)) insert into cjb select '001','数据库', 78 union select '002','信息管理',80 union select '003','专业英语',89 union select '004','数据库' ,62 union select '005','信息管理',50 union select '006','专业英语',56 union select '007','数据库' ,90 union select '008','信息管理',67 union select '009','专业英语',75select 课程名,max(case when rn=1 then 学号 end) as 第一名学号, max(case when rn=2 then 学号 end) as 第二名学号, max(case when rn=1 then 成绩 end) as 第一名成绩, max(case when rn=2 then 成绩 end) as 第二名成绩 from (select * from (select *,rn=ROW_NUMBER() over(partition by 课程名 order by 成绩 desc) from cjb)t where rn<=2 )t group by 课程名
没有测试 select cno, max(case when pm=1 then sno else 0 end), max(case when pm=2 then sno else 0 end), max(case when pm=1 then cno else 0 end), max(case when pm=2 then cno else 0 end) from (
select cno,sno,grade,row_number()over(partition by cno order by grade desc) as pm from stu
)t group by cno
select a.af,b.fenshu,ak,b.kecheng from (select MAX(fenshu)af,MAX( kecheng)ak from Table_3) as a , (select top 2 fenshu,kecheng from Table_3 order by fenshu desc) as b where b.fenshu<a.af 新手来一个不知道对不对求指点
insert into cjb
select '001','数据库', 78 union
select '002','信息管理',80 union
select '003','专业英语',89 union
select '004','数据库' ,62 union
select '005','信息管理',50 union
select '006','专业英语',56 union
select '007','数据库' ,90 union
select '008','信息管理',67 union
select '009','专业英语',75select 课程名,max(case when rn=1 then 学号 end) as 第一名学号,
max(case when rn=2 then 学号 end) as 第二名学号,
max(case when rn=1 then 成绩 end) as 第一名成绩,
max(case when rn=2 then 成绩 end) as 第二名成绩
from
(select *
from (select *,rn=ROW_NUMBER() over(partition by 课程名 order by 成绩 desc) from cjb)t
where rn<=2
)t
group by 课程名
drop table cjb/*
课程名 第一名学号 第二名学号 第一名成绩 第二名成绩
数据库 007 001 90.00 78.00
信息管理 002 008 80.00 67.00
专业英语 003 009 89.00 75.00
*/
select cno,
max(case when pm=1 then sno else 0 end),
max(case when pm=2 then sno else 0 end),
max(case when pm=1 then cno else 0 end),
max(case when pm=2 then cno else 0 end)
from (
select cno,sno,grade,row_number()over(partition by cno order by grade desc) as pm
from stu
)t
group by cno
(select MAX(fenshu)af,MAX( kecheng)ak from Table_3) as a
,
(select top 2 fenshu,kecheng from Table_3 order by fenshu desc) as b
where b.fenshu<a.af
新手来一个不知道对不对求指点
查询表B比表A大的第一条数据
测试数据对不知道有BUG么