[英]How can I get a value corresponding to the maximum average in this SQL exercise?
I tried to solve this exercise, but I'm stuck when it comes to show the CCode where I have the maximum average of students.我试图解决这个练习,但是在显示CCode时我的学生平均人数最多。 I attach the pic of the exercise and the database tables.我附上了练习的图片和数据库表。 Thanks in advance.提前致谢。
Here's my code:这是我的代码:
SELECT CO.TCode, CO.CCode
FROM COURSE CO
WHERE CO.CCode NOT IN(
SELECT CCode
FROM COURSE
WHERE Topic <> 'database')
AND CO.CCode =(
SELECT C1.CCode
FROM (SELECT CCode, AVG(AttendingStudent#) MEDIA
FROM LECTURE
GROUP BY CCode) C1
WHERE MAX(C1.MEDIA) AND C1.CCode = CO.CCode
)
I don't think the maximum in the WHERE clause can work.我认为WHERE子句中的最大值不起作用。
From Oracle 12, you can order the subquery and use FETCH FIRST ROW ONLY
to get the maximum (or FETCH FIRST ROW WITH TIES
if there would be join highest, but then you would need to change from an =
comparison to IN
).从 Oracle 12 开始,您可以订购子查询并使用FETCH FIRST ROW ONLY
来获得最大值(如果连接最高,则FETCH FIRST ROW WITH TIES
,但是您需要从=
比较更改为IN
)。
SELECT CO.TCode,
CO.CCode
FROM COURSE CO
WHERE CO.CCode NOT IN( SELECT CCode
FROM COURSE
WHERE Topic <> 'database')
AND CO.CCode = ( SELECT c.CCode
FROM Course c
INNER JOIN LECTURE l
ON (c.ccode = l.ccode)
WHERE l.TCode = CO.TCode
GROUP BY CCode
ORDER BY AVG(AttendingStudent#) DESC
FETCH FIRST ROW ONLY
)
Otherwise, you can use a HAVING
clause:否则,您可以使用HAVING
子句:
SELECT CO.TCode,
CO.CCode
FROM COURSE CO
WHERE CO.CCode NOT IN( SELECT CCode
FROM COURSE
WHERE Topic <> 'database'
)
AND CO.CCode IN ( SELECT CCode
FROM (
SELECT TCode,
CCode,
AVG(AttendingStudent#) MEDIA
FROM LECTURE
GROUP BY TCode, CCode
) C1
WHERE c1.TCode = CO.TCode
HAVING c1.MEDIA = MAX(C1.MEDIA)
)
Note: Your first sub-query is not correct as you want to find the teacher that has not taught a non-databases course and not the non-databases courses.注意:您的第一个子查询不正确,因为您想找到没有教过非数据库课程而不是非数据库课程的老师。 It's almost correct though as you only need to change the column you are comparing on but I am sure you can correct it.这几乎是正确的,因为您只需要更改要比较的列,但我相信您可以更正它。
Try using the following as subquery:尝试使用以下作为子查询:
SELECT C1.CCode
FROM (SELECT CCode,
AVG(AttendingStudent#) MEDIA
FROM LECTURE
GROUP BY CCode) C1
GROUP BY C1.CCode
HAVING MAX(C1.MEDIA) AND C1.CCode = CO.CCode
You will be aggregating on " C1.MEDIA " and grouping on " C1.CCode ", but the aggregation will just happen inside the HAVING
clause, leaving only the codes for selection.您将在“ C1.MEDIA ”上进行聚合并在“ C1.CCode ”上进行分组,但聚合只会发生在HAVING
子句内,只留下代码供选择。
Some tips on how to use the HAVING
clause here .这里有一些关于如何使用HAVING
子句的提示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.