SQL查询列出最高等级

时间:2016-10-28 04:13:39

标签: sql

我不知道如何编写一个查询来显示所有多次参加相同课程的学生。还列出了该课程的学生最高成绩。我写了这个查询,但我仍然没有看到最高的字母等级。

他希望它看起来像这样:

enter image description here

输入:

TNumber     Course_id   Attempts    Highest grade 
00012345    CSC2110     2           D 
00015366    CSC2110     3           B

我的查询:

select tnumber, courseid, count(*)
from GRADES
group by tnumber, courseid
having count(*) > 1

4 个答案:

答案 0 :(得分:1)

SELECT tnumber, MAX( grade ) AS highest_grade
  FROM GRADES
 WHERE courseid = '123'
 GROUP BY tnumber;

答案 1 :(得分:1)

取决于什么是“最高”等级。如果“A”高于“B”,则必须使用min而不是max,因为字符串排序会给出'A'< 'B'

select tnumber, courseid, count(*), min(grade) as HIGHEST_GRADE
from GRADES 
group by tnumber, courseid 
having count(*)>1

答案 2 :(得分:0)

只需在当前查询中添加max(grade)即可获得每门课程中每位学生的最高分数

select tnumber, courseid, count(*),max(grade) 
from GRADES 
group by tnumber, courseid 
having count(*)>1

答案 3 :(得分:0)

如果您不仅需要学生和课程的最高成绩,而且还需要课程中的最高成绩,您可以使用(ORACLE-语法):

WITH INPUT AS (
  SELECT '123' TNUMBER, 'AA' COURSEID, 'D' GRADE FROM DUAL UNION ALL
  SELECT '123' TNUMBER, 'AA' COURSEID, 'B' GRADE FROM DUAL UNION ALL
  SELECT '123' TNUMBER, 'AA' COURSEID, 'C' GRADE FROM DUAL UNION ALL
  SELECT '234' TNUMBER, 'AA' COURSEID, 'A' GRADE FROM DUAL UNION ALL
  SELECT '234' TNUMBER, 'AA' COURSEID, 'B' GRADE FROM DUAL UNION ALL
  SELECT '123' TNUMBER, 'BB' COURSEID, 'C' GRADE FROM DUAL UNION ALL  
  SELECT '234' TNUMBER, 'BB' COURSEID, 'C' GRADE FROM DUAL UNION ALL  
  SELECT '234' TNUMBER, 'BB' COURSEID, 'D' GRADE FROM DUAL
)
SELECT 
  I1.TNUMBER, 
  I1.COURSEID, 
  COUNT(*), 
  MIN(I1.GRADE), 
  MIN(I2.HIGHEST_GRADE)
FROM INPUT I1
JOIN (SELECT COURSEID, MIN(GRADE) HIGHEST_GRADE FROM INPUT GROUP BY COURSEID) I2
ON I1.COURSEID = I2.COURSEID
GROUP BY I1.TNUMBER, I1.COURSEID
HAVING COUNT(*)>1
;

with子句仅用于创建数据

结果将是

TNUMBER COURSEID    COUNT(*)    MIN(I1.GRADE)   MIN(I2.HIGHEST_GRADE)
123 AA  3   B   A
234 AA  2   A   A
234 BB  2   C   C

234 BB 2 C C