我正在使用這個資料庫:link。
我想寫一個查詢來獲取屬于class 2 (class_id = 2) 并且在特定課程(course_id = 9) 中具有最高平均分和最高學位的學生姓名,如果沒有擁有這些資料的學生然后什么都不回傳。
我設法寫了一半,并獲得了第 2 班平均分最高的學生,但我不知道如何添加第二個條件(課程 9 中的最高學位),我嘗試了很多方法都行不通。這是我的查詢:(抱歉代碼凌亂,我還在學習中)
SELECT s.studentname
FROM students s
JOIN section se
ON s.sectionid = se.sectionid
JOIN courses_student cs
ON s.student_id = cs.student_id
WHERE se.classes_id = 2
GROUP BY s.studentname
HAVING ( Avg(cs.exam_season_one)
Avg(cs.exam_season_two)
Avg(cs.degree_season_one)
Avg(cs.degree_season_two) ) / 4 = (SELECT
Max(( Avg(cs.exam_season_one)
Avg(cs.exam_season_two)
Avg(cs.degree_season_one)
Avg(cs.degree_season_two)
) / 4)
FROM students s
JOIN section se
ON s.sectionid =
se.sectionid
JOIN courses_student cs
ON s.student_id =
cs.student_id
WHERE se.classes_id = 2
GROUP BY s.studentname)
我計算平均值的方法是:
( Avg(cs.exam_season_one)
Avg(cs.exam_season_two)
Avg(cs.degree_season_one)
Avg(cs.degree_season_two) ) / 4
當我計算特定課程學位的方式是:
(cs.exam_season_one
cs.exam_season_two
cs.degree_season_one
cs.degree_season_two ) / 4
那么如何編輯我的查詢以添加第二個條件?或者有比這更好的方法嗎?
PS:我用oracle
uj5u.com熱心網友回復:
您可以找到每個學生的最大值和平均值,然后使用決議函式找到兩個條件的最大值:
SELECT studentname
FROM (
SELECT studentname,
ROW_NUMBER() OVER (ORDER BY avg_degree DESC) AS rn_avg,
ROW_NUMBER() OVER (ORDER BY max_degree DESC) AS rn_max
FROM (
SELECT MAX(s.studentname) AS studentname,
AVG(
cs.exam_season_one cs.exam_season_two cs.degree_season_one cs.degree_season_two
) / 4 AS avg_degree,
MAX(
CASE
WHEN cs.courses_id = 9
THEN cs.exam_season_one cs.exam_season_two cs.degree_season_one cs.degree_season_two
END
) / 4 AS max_degree
FROM students s
JOIN section se
ON s.sectionid = se.sectionid
JOIN courses_student cs
ON s.student_id = cs.student_id
WHERE se.classes_id = 2
GROUP BY s.student_id
)
)
WHERE rn_avg = 1
AND rn_max = 1;
同樣,不要GROUP BY studentname因為您可以有兩個同名的學生。
哪些輸出:
學生姓名 馬赫
sqlfiddle在這里
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/369921.html
