SQL Server平均查询

时间:2015-03-03 11:32:46

标签: sql-server average

有人可以帮我查询平均值吗?

我有这张桌子。

 teacher | class | students | rating
 -----------------------------------
   T1        1      001        6
   T1        1      002        6
   T1        2      003        1
   T1        3      004        1
   T2        1      001        6
   T2        1      002        6
   T2        2      003        1
   T2        3      004        1

如果我Select teacher, class, avg(rating) from table group by teacher, class,那么我明白了:

teacher | class | rating
------------------------
   T1       1     6
   T1       2     1
   T1       3     1
   T2       1     6
   T2       2     1
   T2       3     1

我想要做的是获得该结果的平均rating并将其分组为teacher,即:

teacher | rating
------------------------
   T1      2.66667
   T2      2.66667

因为如果我Select avg(rating) from table group by teacher,我会

teacher | rating
------------------------
   T1      3.5
   T2      3.5

2 个答案:

答案 0 :(得分:2)

你可以这样做:

SELECT teacher,avg(avgrating) as avgrating
FROM
(Select teacher, class, avg(rating) avgrating
from TableName 
group by teacher, class) Temp
GROUP BY teacher

结果:

TEACHER   AVGRATING
T1        2.666666
T2        2.666666

SQL Fiddle中的示例结果。

SELECT T1.teacher,avg(T2.avgrating) as rating
FROM TableName T1 JOIN
(SELECT teacher,class,avg(rating) as avgrating
 FROM TableName T2
 GROUP BY teacher,class) T2 ON T1.teacher=T2.teacher
GROUP BY T1.teacher

SQL Fiddle

答案 1 :(得分:1)

使用嵌套选择:

select teacher , avg(avgr) from
 (Select teacher, class, avg(rating) avgr from table group by teacher, class) qry
group by teacher