我在下面有以下代码,我正在尝试为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
答案 0 :(得分:4)
AVG()
是一个聚合函数,它从多个 行 中获取值并给出它们的平均值。
您尝试平均3 列 。
我的具体情况,可以使用代数来完成。
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
答案 1 :(得分: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
看看它是否适合你?
答案 2 :(得分: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!
)