嗨,我有一个查询要检索这种格式的学生成绩
Id subject class_score total_marks rank subject_type
1 MATLAB 33.80 73.30 11 Core
1 SCIENCE 39.50 83.00 4 Core
1 ENGLISH 37.60 77.60 8 Elective
1 WQP 43.90 77.40 9 Core
1 BDT 42.00 71.50 12 Elective
1 ART 47.10 84.60 2 Elective
1 COMPUTING 26.00 65.50 13 Elective
2 MATLAB 0.00 0.00 14 Core
2 SCIENCE 38.60 73.60 10 Core
2 ENGLISH 43.80 83.30 3 Elective
2 WQP 45.00 89.00 1 Core
2 BDT 41.00 79.50 6 Elective
2 ART 38.00 78.00 7 Elective
2 COMPUTING 40.80 80.80 5 Elective
我希望通过将所有学生的总成绩(核心科目+该学生选修科目的前三名)相加并计算从头到尾的排名来计算每个学生的总成绩。任何人都可以提供帮助吗?谢谢
我当前的
use ods_sms;
SELECT student_id,sum(t.total_marks)score
FROM
(select
student_id,total_marks from tab_exam_tracker
where (subject_type='Core')
union all select t.student_id,t.total_marks from
(select student_id,total_marks from tab_exam_tracker
where subject_type = 'Elective' order by total_marks desc
limit 3) t
) t
GROUP BY student_id
但是得到错误的结果
答案 0 :(得分:1)
SELECT
t.id,
SUM(total_marks) AS Core_Marks,
Elective_Marks
FROM tab_exam_tracker t
INNER JOIN (
SELECT id, SUM(total_marks) as Elective_Marks
FROM (
SELECT
id,
total_marks,
IF(@id <> id, @rank:= 1, @rank:= @rank + 1) as rank,
@id:= id
FROM tab_exam_tracker,
(SELECT @id:= 0 r_id, @rank:= 0 AS r) AS a
WHERE subject_type = 'Elective'
ORDER BY id, total_marks DESC
) as b
WHERE rank <= 3
GROUP BY id
) AS e_marks ON t.id = e_marks.id
GROUP BY t.id, Elective_Marks;