Skip to content

Instantly share code, notes, and snippets.

@johanrex
Created March 15, 2019 13:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johanrex/473c4e35c3ee9705b47f380d2076889c to your computer and use it in GitHub Desktop.
Save johanrex/473c4e35c3ee9705b47f380d2076889c to your computer and use it in GitHub Desktop.
SQL moving average
WITH cte
AS (SELECT
1 AS n -- anchor member
,Cast(Cast(CRYPT_GEN_RANDOM(4) as INT) as Float) AS rnd
UNION ALL
SELECT
n + 1 -- recursive member
,Cast(Cast(CRYPT_GEN_RANDOM(4) as INT) as Float)
FROM cte
WHERE n < 50 -- terminator
)
SELECT
n
,rnd
,AVG(rnd) OVER(ORDER BY n ASC ROWS 2 PRECEDING) AS MA3
FROM cte;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment