Skip to content

Instantly share code, notes, and snippets.

@davidsheardown
Created June 10, 2020 06:28
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 davidsheardown/8dd822972e2b971bc0cd2426f55f56fe to your computer and use it in GitHub Desktop.
Save davidsheardown/8dd822972e2b971bc0cd2426f55f56fe to your computer and use it in GitHub Desktop.
/*
Using a CTE, we can iterate through to get the previous row in order to calculate and keep
a running total
*/
WITH PrevRow
AS (SELECT Acolumn,
Bcolumn,
HoldingColumn = Bcolumn,
RunningTotal = HoldingColumn
FROM Atable
WHERE ConditionColumn = 0
UNION ALL
SELECT A.N,
A.B,
E = A.B * ( 1 - PrevRow.RunningTotal ),
RunningTotal = A.B * ( 1 - PrevRow.RunningTotal ) + PrevRow.RunningTotal
FROM PrevRow
JOIN A
ON A.N = R.N + 1)
SELECT N,
B,
E = CAST(E AS DECIMAL(10,9))
FROM PrevRow
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment