码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2014-07-07 19:03:03      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   数据   art   

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

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位的记录,并按学科,成绩排序

标签:des   style   blog   color   数据   art   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!