首页 > 其他 > 详细

查询每门学科成绩在前2位的记录,并按学科,成绩排序

时间:2014-07-07 19:02:06      阅读:330      评论:0      收藏:0      [点我收藏+]

现在有学生成绩表,结构如下

Create Table StuAchievement 
(
      StuId varchar(8),
      CourseId varchar(10),
      Achievement int
)

数据就自己动动手录入吧

SELECT * FROM StuAchievement A
WHERE 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 A
WHERE 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

或者

--运用CTE
WITH 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<=2
ORDER BY a.CourseId,a.Achievement DESC

 

查询每门学科成绩在前2位的记录,并按学科,成绩排序,布布扣,bubuko.com

查询每门学科成绩在前2位的记录,并按学科,成绩排序

原文:http://www.cnblogs.com/DonnyPeng/p/3813428.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!