求一句SQL

Eri 2007-01-12 07:59:40
CREATE TABLE [dbo].[STUDENT]
(
[student_id] varchar(10) NOT NULL,--学号
[course_id] varchar(8) NOT NULL,--课程编号
[achievement] int NOT NULL--该课成绩
)

列出每门课程成绩前两名学生的学号,课程编号,该课成绩
...全文
182 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
Eri 2007-01-12
  • 打赏
  • 举报
回复
marco08(天道酬勤)

能解释一下嘛?没怎么看懂。
Eri 2007-01-12
  • 打赏
  • 举报
回复
两句都只能查出第一名,
本来我想自己该一下的,不过没改出来,所以跑回来问你了。
marco08 2007-01-12
  • 打赏
  • 举报
回复

CREATE TABLE [dbo].[STUDENT]
(
[student_id] varchar(10) NOT NULL,--学号
[course_id] varchar(8) NOT NULL,--课程编号
[achievement] int NOT NULL--该课成绩
)

insert student select '001', 'A001', 80
insert student select '001', 'B001', 60
insert student select '001', 'C001', 66

insert student select '002', 'A001', 82
insert student select '002', 'B001', 65
insert student select '002', 'C001', 78

insert student select '003', 'A001', 88
insert student select '003', 'B001', 58
insert student select '003', 'C001', 60

select * from student A
where (select count(*) from student where course_id=A.course_id and achievement>A.achievement)<2
order by course_id, achievement desc

--result
student_id course_id achievement
---------- --------- -----------
003 A001 88
002 A001 82
002 B001 65
001 B001 60
002 C001 78
001 C001 66

(6 row(s) affected)

zjcxc 元老 2007-01-12
  • 打赏
  • 举报
回复
第1种查询, 如果最高成绩相同, 且超过2名, 则会列出所有最高成绩的
第2种查询不会有此问题.
zjcxc 元老 2007-01-12
  • 打赏
  • 举报
回复
select * from student a
where [student_id] in(
select top 1 [student_id] from student
where [course_id] = a.[course_id]
order by achievement desc)
zjcxc 元老 2007-01-12
  • 打赏
  • 举报
回复

select * from student a
where achievement in(
select top 1 achievement from student
where [course_id] = a.[course_id]
order by achievement desc)

34,576

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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