首页 > 代码库 > 查询每门学科成绩在前2位的记录,并按学科,成绩排序
查询每门学科成绩在前2位的记录,并按学科,成绩排序
现在有学生成绩表,结构如下
Create Table StuAchievement ( StuId varchar(8), CourseId varchar(10), Achievement int)
数据就自己动动手录入吧
SELECT * FROM StuAchievement AWHERE EXISTS( SELECT TOP 1 * FROM StuAchievement b WHERE a.CourseId=b.CourseId AND b.Achievement >a.Achievement HAVING COUNT(0)<=1)ORDER BY a.CourseId,a.Achievement DESC
或者
SELECT * FROM StuAchievement AWHERE NOT EXISTS( SELECT TOP 1 * FROM StuAchievement b WHERE a.CourseId=b.CourseId AND b.Achievement >a.Achievement HAVING COUNT(0)>=2)ORDER BY a.CourseId,a.Achievement DESC
或者
--运用CTEWITH temp AS ( SELECT StuId,CourseId,ROW_NUMBER() OVER (PARTITION BY CourseId ORDER BY CourseId,Achievement DESC) AS rowId FROM StuAchievement)SELECT * FROM StuAchievement a,temp b WHERE a.StuId=b.StuId AND a.CourseId=b.CourseId AND b.rowId<=2ORDER BY a.CourseId,a.Achievement DESC
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。