In Postgresql
(version 10), following sql select all rows order by the avg_grade
.
-- query - students list, order by average grade,
select s.student_id, s.student_name, avg(ce.grade) as avg_grade
from students as s
left join course_enrollment as ce on s.student_id = ce.student_id
group by s.student_id
order by avg_grade desc NULLS LAST;
Relevant tables
students:
create table students (
student_id bigserial not null primary key,
student_name varchar(200) not null,
created timestamp default CURRENT_TIMESTAMP not null
);
course_enrollment:
-- create table,
create table course_enrollment
(
course_id bigint not null,
student_id bigint not null,
grade float not null,
created timestamp default CURRENT_TIMESTAMP not null,
unique (course_id, student_id)
);
Questions:
- How to retrieve only the top n% (e.g 10%) of rows, whose
avg_grade
have the highest values?
Wondering is there a window function to do this, or a sub query is required?
BTW:
- This is different from Postgresql : How do I select top n percent(%) entries from each group/category
Because that one want top n% in each group, thus it could use partitions in thewindow functions
.
But this one want the top n% overall, thusgroup by
is required.