嘿伙计们,我有一个SQL语句,可以获取不同活动类型(家庭作业,测验等)的等级,如果该类型的分数最低,则会下降,否则,它仍然存在。错误在下面和SQL代码一样。
SELECT Student.firstName, Student.lastName, 'Grades' =
CASE
WHEN Grades.activityType = 'Homework' THEN
CASE WHEN Policy.drop_hw = 1 THEN
(AVG(SUM(Grades.grade) - MIN(Grades.grade))) * (Policy.homework / 100)
ELSE
(AVG(Grades.grade) * (Policy.homework / 100))
END
END, Course.courseNum, Course.sectNum, Grades.activityType
FROM ...
以下是我遇到的错误:
- Cannot perform an aggregate function on an expression containing an aggregate or a subquery.
- Column 'Policy.drop_hw' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
答案 0 :(得分:3)
研究分析功能。 (SO question,Oracle documentation)。
这样的事情:
AVG(Grades.grade) OVER (PARTITION BY Grades.student_id) AS avg_of_grades
和
(AVG(SUM(Grades.grade) - MIN(Grades.grade))) OVER (PARTITION BY Grades.student_id) AS avg_grades_with_drop
在您的情况下使用任何有意义的内容设置分区;我们无法分辨,因为您在示例中省略了FROM ...
。
然后,您可以在CASE
语句中的任何计算中使用这些列别名。
答案 1 :(得分:1)
如果你只需要降低一个最低等级(如果有关系)
SELECT student_id, AVG(grade)
FROM (
SELECT *, ROW_NUMBER() OVER (PARTITION BY student_id ORDER BY grade) rn
FROM my_tables
)
WHERE NOT (drop_hw = 1 AND rn = 1)
GROUP BY
student_id
如果你需要放弃所有最低等级:
SELECT student_id, AVG(grade)
FROM (
SELECT *, MIN(grade) OVER (PARTITION BY student_id) mingrade
FROM my_tables
)
WHERE NOT (drop_hw = 1 AND grade = mingrade)
GROUP BY
student_id
答案 2 :(得分:0)
sum-operator给出一个结果(每组)。 min-operator也是。那么avg-operator聚合应该是什么?