2

我在下面有以下代码,我正在尝试获取 3 列的 AVG。

 SELECT 
    (SUM(score) * .3) As score_a,
    (SUM(score) * .6) As score_b,
    (SUM(score) * .8) As score_c

     --now I want to get the AVG of the above scores
    AVG(score_a + score_b + score_c) As avg_score
 FROM score_table

但这不起作用。我得到的错误是“无效的列名 score_a”。我正在使用 SQL Server 2008

4

3 回答 3

4

AVG()是一个聚合函数,它从多中获取值并给出它们的平均值。

您正在尝试平均 3 columns

在您的具体情况下,可以使用代数来完成。

SELECT 
  (SUM(score) * .3)                       As score_a,
  (SUM(score) * .6)                       As score_b,
  (SUM(score) * .8)                       As score_c,
  (SUM(score) * ((0.3 + 0.6 + .8) / 3.0)) As score_avg
FROM
  score_table

在更一般的情况下,您会受到以下事实的限制:您无法引用刚刚在另一列中定义的列......

SELECT
  a + 1      AS inc_a,
  inc_a * 2  AS this_is_invalid
FROM
  your_table

您要么需要重复自己,要么使用子查询...

重复

SELECT 
  (SUM(score) * .3)                                                 As score_a,
  (SUM(score) * .6)                                                 As score_b,
  (SUM(score) * .8)                                                 As score_c,
  ((SUM(score) * .3) + (SUM(score) * .3) + (SUM(score) * .3)) / 3.0 As score_avg
FROM
  score_table

子查询

SELECT
  score_a,
  score_b,
  score_c,
  (score_a + score_b + score_c) / 3.0 AS score_avg
FROM
(
  SELECT 
    (SUM(score) * .3)                                               As score_a,
    (SUM(score) * .6)                                               As score_b,
    (SUM(score) * .8)                                               As score_c
  FROM
    score_table
)
  AS data
于 2012-04-25T18:29:41.323 回答
0

你能试试:

 SELECT 
    (SUM(score) * .3) As score_a,
    (SUM(score) * .6) As score_b,
    (SUM(score) * .8) As score_c,
    AVG(score_a + score_b + score_c) As avg_score
 FROM score_table

看看这对你有用吗?

于 2012-04-25T18:23:54.043 回答
0

有手动进行平均的蛮力方法,但它不会像您添加列一样缩放。:)

SELECT CAST((score_a + score_b + score_c) / 3 AS DECIMAL(20,2)) As avg_score,
       score_a,
       score_b,
       score_c
FROM (
    SELECT (SUM(score) * .3) As score_a,
           (SUM(score) * .6) As score_b,
           (SUM(score) * .8) As score_c
    FROM score_table
    GROUP BY userid, gameid --Whatever you're grouping by here!
)
于 2012-04-25T18:24:20.347 回答