内连接和Avg()函数

时间:2015-02-05 18:21:09

标签: sql sql-server inner-join average

我正在使用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.score>(select avg(b.score) From b
Where a.class=b.class 
group by class);

我认为“a.class = b.class”可能存在一些问题,请问我的内连接方法是否正确?我还可以使用加入吗?

3 个答案:

答案 0 :(得分:2)

尝试这样的事情:

 Select a.StudentName, TableAvg.class, a.score
  From TableA a
  inner Join  (select class, avg(score) as AvgScore
        From TableA 
        group by class)  TableAvg
  On a.score >  TableAvg.AvgScore
  and a.class = TableAvg.class   

未经测试的代码......

答案 1 :(得分:1)

示例数据:

SELECT 'Jim' AS StudentName, 'A1' AS Class, 80 AS Score
INTO #Temporary
UNION ALL
SELECT 'Ann', 'A1', 83
UNION ALL
SELECT 'Bill', 'A2', 90

实际查询(无需连接表两次)

SELECT *
FROM (
    SELECT StudentName, Class, Score, AVG(CAST(Score AS FLOAT)) OVER(PARTITION BY Class) AS AvgScore
    FROM #Temporary
) AS T
WHERE T.Score >= T.AvgScore

答案 2 :(得分:0)

您需要将Table b(items)添加到SELECT 比如b.score , b.class