求每门功课成绩最好的前两名?

hello926 2010-05-19 06:44:36
create table stu(
sno varchar(2),
cursorid varchar(2),
grade decimal(18,0))
insert stu
select 1,1,99 union all
select 2,1,98 union all
select 3,1,100 union all
select 4,2, 88 union all
select 5,2,87 union all
select 6,2,88 union all
select 7,3,99 union all
select 8,3,98 union all
select 9,3,100
...全文
230 6 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhengduan964532 2010-05-19
  • 打赏
  • 举报
回复
慢了,郁闷
zhengduan964532 2010-05-19
  • 打赏
  • 举报
回复

IF object_id('stu')IS NOT NULL DROP TABLE stu
create table stu(
sno varchar(2),
cursorid varchar(2),
grade decimal(18,0))
insert stu
select 1,1,99 union all
select 2,1,98 union all
select 3,1,100 union all
select 4,2, 88 union all
select 5,2,87 union all
select 6,2,88 union all
select 7,3,99 union all
select 8,3,98 union all
select 9,3,100


SELECT * FROM stu


;WITH romance
AS
(
SELECT sno,cursorid,grade,num=row_number()OVER (PARTITION BY cursorid ORDER BY grade desc )
FROM stu
)
SELECT * FROM romance
WHERE num<=2
feixianxxx 2010-05-19
  • 打赏
  • 举报
回复
create table stu
(
sno varchar(2),
cursorid varchar(2),
grade decimal(18,0))
insert stu
select 1,1,99 union all
select 2,1,98 union all
select 3,1,100 union all
select 4,2, 88 union all
select 5,2,87 union all
select 6,2,88 union all
select 7,3,99 union all
select 8,3,98 union all
select 9,3,100
go
select cursorid,sno,grade
from
(
select rn=row_number() over(partition by cursorid order by grade desc ),*
from stu
) k
where rn between 1 and 2
/*
cursorid sno grade
-------- ---- ---------------------------------------
1 3 100
1 1 99
2 4 88
2 6 88
3 9 100
3 7 99
*/
feixianxxx 2010-05-19
  • 打赏
  • 举报
回复
select sno,cursorid,grade
from
(
select rn=row_number() over(partition by cursorid order by grade desc )
from stu
) k
where rn between 1 and 2

根据需求 你可以将上面的row_number 换成RANK() over()... 或者 dense_rank()....

27,582

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧