我正在使用sql-server。我有一个类似
的表StudentName Class score
Jim a1 80
Ann a1 83
Bill a2 90
我想选择分数高于他/她班级平均分的学生。这是我的代码:
Select a.StudentName
From Table a
inner Join Table b
On a.class=b.class
where a.score>(select avg(b.score) From b
group by class);
内连接方法对我来说很奇怪。请问它是否正确?有没有更好的方法来实现这一目标?
答案 0 :(得分:2)
您已经关闭,但您可以限制子查询并取消加入:
Select a.StudentName
From Table a
where a.score > (
select avg(b.score) score
From Table b
where b.class = a.class);
答案 1 :(得分:0)
怎么样:
;with ClassAverages as (
select Class, AVG(score) as AVGScore FROM Table GROUP BY Class
)
SELECT StudentName FROM Table student
INNER JOIN ClassAverages ON ClassAverages.Class=student.Class
WHERE student.score>ClassAverages.AVGScore