平均值之和

时间:2016-06-24 18:51:38

标签: sql sql-server

使用此子查询,我做错了,因为我没有在LastSixMosAvg中获得正确的平均值。

JOIN
  (SELECT Avg(LastSix) as LastSixMosAvg,id
  FROM (SELECT t.id,Sum(t.total) as LastSix
          FROM table t
          WHERE t.Month Between @6mosStart and @enddate
          group by t.id)t
    Group by id) d
          ON d.ID=a.ID

该查询以特定ID生成此结果。

Month           Total   LastSixMosAvg
Month 1           325   1,367
Month 2            30   1,367
Month 3           330   1,367
Month 4           336   1,367
Month 5           220   1,367
Month 6           126   1,367

而是在LasSixMos Avg我应该看到$228

1 个答案:

答案 0 :(得分:2)

您的查询是对“总计”列的 总和 求平均值。总和为1,367,它是每个ID的常量,因此平均正确返回1,367。

尝试选择“总计”列本身的平均值:

INNER JOIN
(
    SELECT t.ID, Avg(t.Total) as LastSixMosAvg
    FROM MyTable t
    WHERE t.Month Between @6mosStart and @enddate
    GROUP BY t.ID
) d
    ON d.ID = a.ID

示例:

declare @t table
(
    [ID] int,
    [Month] int,
    Total int,
    primary key clustered([ID], [Month])
)
insert into @t values
(1, 1, 325),
(1, 2, 30),
(1, 3, 330),
(1, 4, 336),
(1, 5, 220),
(1, 6, 127)

declare @6mosStart int = 1, @enddate int = 6
SELECT t.ID, Avg(t.Total) as LastSixMosAvg
FROM @t t
WHERE t.Month Between @6mosStart and @enddate
GROUP BY t.ID

-- Results:
-- ID LastSixMosAvg
-- 1  228