嗨,我有一个看起来像这样的架构
我做了两个必须执行的查询:
找到教授最多数量的不同课程的前4名教师的姓名。同时显示所教课程的总数。
InstructorName
,NumberOfCoursesTaught
NumberOfCoursesTaught
找到参加课程最多的前2名学生。
输出列:S_ID
,StudentName
,NumberOfCourses
降序排列:NumberOfCourses
对于查询1,我写道:
SELECT name AS InstructorName, count(course_id) AS NumberOfCourses
FROM Teaches
WHERE name IN (SELECT name FROM Instructor where Instructor.i_id = Teaches.i_id)
GROUP BU i_id
ORDER BY COUNT(course_id) DESC;
对于查询2,我写了
SELECT s_id as S_ID, name as StudentName, count(course_id) as NumberOfCourses
FROM Takes
WHERE name IN (SELECT name FROM Student WHERE Takes.s_id = Student.s_id)
GROUP BY s_id
ORDER BY COUNT(course_id) DESC;
都说:
“ NAME”的标识符无效
答案 0 :(得分:1)
我建议您应该使用其他逻辑来构建查询。这是第一个查询的演示;从那里开始,您应该能够创建第二个查询(也许可以将其发布为答案?)。
从汇总查询开始,该查询根据Teaches
表来计算每个教师ID的教课数量:
SELECT i_id, COUNT(*) cnt FROM Teaches GROUP BY i_id
然后使用窗口函数ROW_NUMBER()
通过减少计数来对每个记录进行排名:
SELECT i_id, cnt, ROW_NUMBER() OVER(ORDER BY cnt DESC) rn
FROM (SELECT i_id, COUNT(*) cnt FROM Teaches GROUP BY i_id) t
剩下要做的就是获取教师姓名(JOIN ON Instructor
)并过滤前4条记录
SELECT i.name InstructorName, x.cnt NumberOfCoursesTaught
FROM (
SELECT i_id, cnt, ROW_NUMBER() OVER(ORDER BY cnt DESC) rn
FROM (SELECT i_id, COUNT(*) cnt FROM Teaches GROUP BY i_id) t
) x
INNER JOIN Instructor i ON i.i_id = x.i_id
WHERE x.rn <= 4
ORDER BY x.cnt desc