AVG上不止一列

时间:2012-03-02 06:51:18

标签: sql sql-server tsql

我有一张表在一栏中保存了课程的成绩,在另一栏中保存了该课程的比例,然后我想用比率计算课程的平均值,我写这些代码但我面临错误,请帮忙我

select SUM((grade * ratio) / SUM(ratio)) as averageOfCourses
from myTable

3 个答案:

答案 0 :(得分:2)

select (SUM(grade * ratio) / SUM(ratio)) as averageOfCourses from myTable 

答案 1 :(得分:1)

您的问题可能是错误的括号。

SELECT SUM(grade * ratio) / SUM(ratio) AS averageOfCourses
  FROM myTable

如果你真的想要用SUM除以值的和,那么你必须更加努力地工作;你不能直接聚合聚合。

要做你写的东西,你必须把它重写为:

SELECT SUM((grade * ratio) / sum_ratio) AS averageOfCourses
  FROM (SELECT grade, ratio, SUM(ratio) AS sum_ratio
          FROM myTable
         GROUP BY grade, ratio) AS precalculation

(标准SQL需要最终AS,但对此查询没有任何贡献。)

在这种情况下,我甚至不确定它会给出不同的答案。

答案 2 :(得分:1)

declare @sum float = (select sum(ratio) from myTable)
select sum( grade * ratio / @sum ) as averageOfCourses from myTable