我正在尝试将sql查询写入下面的学生标记表,我们需要从中计算每个学生成绩的标记汇总。
以下是获得所需输出的规则/条件:
如果" A"学生成绩存在然后不考虑" B"年级。 并进行聚合。不要在输出表中填写B等级。
如果" A"学生不在给定的表格中,然后检查" B"年级学生并进行聚合。
我尝试了一些东西而没有得到所需的输出。但是我仍然很难选择正确的方法来获得所需的输出。
例如:这是我的表格和所需的查询。
select exam,
sum(CASE WHEN students_grade in ("A") THEN marks
ELSE
students_grade in ("B") THEN marks END) aggregate
from input_table
group by exam
input_table:
student_grade Exam Marks
------------------------------------------------------
A test_1 10.00
B test_1 10.00
A test_1 10.00
A test_1 20.00
A test_1 20.00
B test_1 30.50
期望的输出:
student_grade Exam aggregate
---------------------------------------------------------
A test_1 60.00
请更正以上查询以获得所需的输出/以应用上述条件,提前致谢
答案 0 :(得分:0)
select i.students_grade, i.exam, sum(i.marks) as aggregate
from input_table i
inner join
(select exam, min(students_grade) as mng
from input_table
group by exam) t
on t.exam = i.exam and t.mng = i.students_grade
group by i.students_grade, i.exam
假设您正在寻找每个考试中的最佳成绩(按min
排序),上述查询应该有效。
答案 1 :(得分:0)
SELECT student_grade, exam, sum(marks) AS aggregate
FROM input_table
GROUP BY student_grade, exam
答案 2 :(得分:0)
select
left(MixCode, 1) as student_grade,
exam,
sum(
case
when MixCode in ('AA', 'BB') then marks
when MixCode = 'AB' and student_grade = 'A' then marks
end
) as aggregate
from
input as i inner join
(
select exam, min(student_grade) + max(student_grade) as MixCode
from input
group by exam
) as m
on m.exam = i.exam
group by exam
如果您要考虑其他成绩组合,上述查询可能效果最佳。我认为下面的查询也可以。这里的想法实际上是说你只想要每个考试的最高分数而忽略所有其他考试:
select min(student_grade) as student_grade, exam, sum(marks)
from input as i
where student_grade = (select min(student_grade) from input as i2 where i2.exam = i.exam)
group by exam
*请记住min()
表示更高的成绩。
答案 3 :(得分:0)
cron
答案 4 :(得分:0)
select (case when Amarks>0 then Amarks else Bmarks end) as aggregate,exam
from(
SELECT sum( case when student_grade='A' then marks else 0 end )as Amarks
, sum( case when student_grade='B' then marks else 0 end )as Bmarks
,exam
FROM input_table
GROUP BY exam
) a