如何列出所有在SQL表中获得高于其平均成绩的学生?我们有6个group_ids,因此有六种不同的平均成绩。
group_id student grade 1 James 85 1 Adam 96 2 Tom 56 2 Jane 89 2 Anny 90
结果:
group_id student grade 1 Adam 96 2 Jane 89 2 Anny 90
答案 0 :(得分:2)
ashkufaraz的答案更接近但不太正确
select group_id,student,grade from students one where grade >
(select avg(grade) from students two where two.group_id = one.group_id)
答案 1 :(得分:0)
问题只是标记SQL,所以这是使用标准SQL的答案:
一种选择是使用窗口函数:
select group_id,student,grade
from (
select group_id,student,grade,
avg(grade) over (partition by group_id) as group_avg
from studends
) t
where grade > group_avg;
这样做的另一个好处是,您还可以显示组平均值以及结果,而无需额外的连接或子选择。