内部连接和 Avg( ) 函数
Inner join and Avg( ) function
我正在使用 sql-server.I table 看起来像
StudentName Class score
Jim a1 80
Ann a1 83
Bill a2 90
我想要 select 个成绩高于 his/her class 平均分的学生。这是我的代码:
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);
我认为"where a.class=b.class"中可能存在一些问题,请问我的内部连接方法是否正确?我也可以使用 join 吗?
您需要将 Table b(items)
添加到您的 SELECT
喜欢 b.score , b.class
尝试这样的事情:
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
未经测试的代码...
示例数据:
SELECT 'Jim' AS StudentName, 'A1' AS Class, 80 AS Score
INTO #Temporary
UNION ALL
SELECT 'Ann', 'A1', 83
UNION ALL
SELECT 'Bill', 'A2', 90
实际查询(无需加入table两次)
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
我正在使用 sql-server.I table 看起来像
StudentName Class score
Jim a1 80
Ann a1 83
Bill a2 90
我想要 select 个成绩高于 his/her class 平均分的学生。这是我的代码:
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);
我认为"where a.class=b.class"中可能存在一些问题,请问我的内部连接方法是否正确?我也可以使用 join 吗?
您需要将 Table b(items)
添加到您的 SELECT
喜欢 b.score , b.class
尝试这样的事情:
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
未经测试的代码...
示例数据:
SELECT 'Jim' AS StudentName, 'A1' AS Class, 80 AS Score
INTO #Temporary
UNION ALL
SELECT 'Ann', 'A1', 83
UNION ALL
SELECT 'Bill', 'A2', 90
实际查询(无需加入table两次)
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