2015-02-05 65 views
0

我使用SQL-server.I有一個表,看起來像內連接和AVG()函數

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」,是我的內連接方法正確這裏好嗎?我也可以使用連接嗎?

+1

感謝您的回覆。這是我正在使用的sql-server, – user4441082 2015-02-05 18:39:52

回答

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 

未經測試的代碼...

+0

感謝您的回覆。 TableAvg.class工作嗎? TableAvg是我將它添加到代碼中的平均分數 – user4441082 2015-02-05 18:48:04

+0

。 – tember 2015-02-05 18:54:12

+0

如果你覺得它解決了你的困境,請標記爲答案 – tember 2015-02-05 19:50:18

0

您需要添加Table b(items)SELECT
b.score , b.class

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