在SQL

时间:2018-05-14 08:45:34

标签: sql oracle

我想写一个查询,列出总课程学分最高的学生。结果还应显示学生注册的课程数量以及最高总学分。

我的查询是

SELECT 
COUNT(COUNT(COURSE.COURSE_NO)) AS "Number of courses", 
MAX(SUM(COURSE.CREDITS)) AS "Total Credits"
FROM 
STUDENT
JOIN ENROLLMENT 
ON ENROLLMENT.S_ID = STUDENT.S_ID
JOIN COURSE_SECTION
ON COURSE_SECTION.C_SEC_ID = ENROLLMENT.C_SEC_ID
JOIN COURSE
ON COURSE.COURSE_NO = COURSE_SECTION.COURSE_NO
GROUP BY STUDENT.S_ID;

结果是:

Number of courses Total Credits
----------------- -------------
            6            21

属于特定学生。

如何显示学生ID以及结果?当我将STUDENT.S_ID放入SELECT子句时,它会触发错误,而不是单个组函数'。

1 个答案:

答案 0 :(得分:0)

我相信你想要:

SELECT e.*
FROM (SELECT e.S_ID
             COUNT(*) as num_courses,
             SUM(c.CREDITS) AS total_credits,
             RANK() OVER (ORDER BY SUM(c.CREDITS)) as seqnum
      FROM ENROLLMENT e JOIN
           COURSE_SECTION cs
           ON cs.C_SEC_ID = e.C_SEC_ID JOIN
           COURSE c
           ON c.COURSE_NO = cs.COURSE_NO
      GROUP BY e.S_ID
     ) e
WHERE seqnum = 1;

这将返回所有学生的最高学分数。毕竟,可能会有不止一个这样的学生。

其他说明:

  • 表别名使查询更易于编写和阅读。
  • 不需要表STUDENTS,因为学生ID在ENROLLMENT
  • 使用简单的列别名,因此您不必转义这些名称。