我正在解決一個任務,我設法找到了一個解決方案,但我不確定這是否是撰寫此查詢的最佳方式
SELECT
students.studentname,
CASE
WHEN (AVG(courses_student.exam_season_one)
AVG(courses_student.exam_season_two)
AVG(courses_student.degree_season_one)
AVG(courses_student.degree_season_two)) / 4 >= 80
THEN 'EXCELLENT'
WHEN (AVG(courses_student.exam_season_one)
AVG(courses_student.exam_season_two)
AVG(courses_student.degree_season_one)
AVG(courses_student.degree_season_two)) / 4 >= 70
THEN 'VERY GOOD'
WHEN (AVG(courses_student.exam_season_one)
AVG(courses_student.exam_season_two)
AVG(courses_student.degree_season_one)
AVG(courses_student.degree_season_two)) / 4 >= 60
THEN 'GOOD'
WHEN (AVG(courses_student.exam_season_one)
AVG(courses_student.exam_season_two)
AVG(courses_student.degree_season_one)
AVG(courses_student.degree_season_two)) / 4 >= 50
THEN 'ACCEPTABLE'
ELSE 'FAIL'
END AS GRADE
FROM
courses_student
JOIN
students ON students.student_id = courses_student.student_id
GROUP BY
students.studentname
正如你所看到的,我重復了這個:
WHEN (AVG(courses_student.exam_season_one)
AVG(courses_student.exam_season_two)
AVG(courses_student.degree_season_one)
AVG(courses_student.degree_season_two)) / 4
四次!它看起來很亂,所以有沒有辦法讓它更短,比如只寫一次,然后只用一個詞?(我嘗試使用“AS”它沒有用)
uj5u.com熱心網友回復:
出于清晰、測驗和除錯目的,您可以通過將其包含在子查詢中來避免重復相同的長運算式。例如:
select studentname,
case when av >= 80 then 'EXCELLENT'
when av >= 70 then 'VERY GOOD'
when av >= 60 then 'GOOD'
when av >= 50 then 'ACCEPTABLE'
else 'FAIL'
end as grade
from (
SELECT s.studentname,
(avg(cs.exam_season_one) avg(cs.exam_season_two)
avg(cs.degree_season_one) avg(cs.degree_season_two)) / 4 as av
FROM courses_student cs
JOIN students c on s.student_id = cs.student_id
GROUP BY s.studentname
) x
它看起來并不短,但更容易發現錯誤并修復它。
uj5u.com熱心網友回復:
您可以像這樣嘗試 CTE:
與 CTE(SELECT Students.studentname, AVG(courses_student.exam_season_one) AVG(courses_student.exam_season_two) AVG(courses_student.degree_season_one) AVG(courses_student.degree_season_two)) / 4 As平均課程sours_student.exam_season_one = AVG(courses_student.degree_season_two)) .student_id GROUP BY student.studentname ) 選擇學生姓名,如果平均值 >= 80 然后是“優秀”,當平均值 >= 70 然后“非常好”,當平均值 >= 60 然后“良好”,當平均值 >= 50 然后“可接受”否則'FAIL' 以 CTE 的成績結束
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/367855.html
標籤:sql 甲骨文 oracle-sqldeveloper
上一篇:OracleSQL:將當前行和前兩行上的條件嵌套的excel轉換為SQL
下一篇:創建變數型別表如何設定欄位名稱?
