Skip to content

Instantly share code, notes, and snippets.

@alex-groshev
Last active August 29, 2015 14:17
Show Gist options
  • Save alex-groshev/efcc2c1a958df0c41e00 to your computer and use it in GitHub Desktop.
Save alex-groshev/efcc2c1a958df0c41e00 to your computer and use it in GitHub Desktop.
Moving Averages / MS SQL 2012
-- Cumulative Moving Average (CMA) and Simple Moving Average (SMA)
SELECT
d.Value,
AVG(d.Value) OVER (PARTITION BY d.MetricId ORDER BY d.Id) AS 'CMA',
AVG(d.Value) OVER (PARTITION BY d.MetricId ORDER BY d.Id ROWS 2 PRECEDING) AS 'SMA(3)',
AVG(d.Value) OVER (PARTITION BY d.MetricId ORDER BY d.Id ROWS 6 PRECEDING) AS 'SMA(7)'
FROM DailyTotals AS d
WHERE
d.DateId >= '20150101'
AND d.MetricId = 2;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment