I think it may work with 2 adjustments to the correlated subquery.
- Subtract 11 months in the
DateAdd()
expression. - Include another
WHERE
condition to limit the average to the samerep
as the current row of the parent (containing) query.
SELECT
p.rep,
p.cyc_date,
(
SELECT Avg(Q.amt)
FROM production AS Q
WHERE
Q.rep = p.rep
AND
Q.cyc_date BETWEEN DateAdd("m", -11, p.cyc_date)
AND p.cyc_date
) AS [12moavg]
FROM production AS p;
Correlated subqueries can be slow. Make sure to index rep
and cyc_date
to limit the pain with this one.