如何获得以下问题的正确结果:
数据结构
主题有代码和描述。学生有一个名字。成绩与学生,学科和年级有关。
成绩表
grades_id|student_id|subject_id|grade
1 | 1 | 1 |85
2 | 1 | 2 |0
3 | 1 | 3 |91
4 | 1 | 4 |86
5 | 1 | 5 |89
6 | 1 | 6 |0
7 | 2 | 1 |0
8 | 2 | 2 |84
9 | 2 | 3 |0
10 | 2 | 4 |87
11 | 2 | 5 |89
12 | 2 | 6 |80
13 | 3 | 1 |88
14 | 3 | 2 |90
15 | 3 | 3 |87
16 | 3 | 4 |85
17 | 3 | 5 |84
18 | 3 | 6 |79
19 | 4 | 1 |86
20 | 4 | 2 |88
21 | 4 | 3 |84
22 | 4 | 4 |90
23 | 4 | 5 |83
24 | 4 | 6 |81
学生表
student_id | name
1 | Samuel Canizares
2 | Adrian Jacalan
3 | Renan Villamor
4 | Raymond Bongo
主题表
subject_id | subject_code | description
1 | 122345 | Science
2 | 113345 | Mathematics
3 | 133445 | Religion
4 | 111245 | English
5 | 142355 | PE
6 | 144521 | Social Studies
我正在使用PostgreSQL
这是我对第1号问题的回答:
select sb.subject_code,sb.description,gr.grade
from grade g inner join (select distinct on (grade) grade,grade_id from grade
) gr
on gr.grade_id = g.grade_id
left join student st
on st.student_id = g.student_id
left join subject sb
on sb.subject_id = g.subject_id
order by 3 desc limit 3
问题是如何才能获得每个科目的前三名?我只限于所有科目的高年级