I need to update the same table I'm using to create a recursive cte. The cte works as a select statement, but I can't get it to actually insert those values back into the table.
My code is below- basically I want to:
UPDATE tbl_1minSET tbl_1min.ema9 = x.NewEmaWHERE x.id = tbl_1min.id
Can anyone help? I'd really appreciate it!
SET @NDays := 9;WITH RECURSIVE anchor AS ( SELECT a1.id, a1.close, a1.ema9 FROM tbl_1min a1),x AS ( SELECT anchor.id, anchor.close, x2.ema9 AS PrevEma, anchor.ema9, anchor.ema9 AS NewEma FROM anchor INNER JOIN anchor x2 ON anchor.id - 1 = x2.id WHERE anchor.id = @NDays -- FIRST SEED ROWUNION SELECT anchor.id, anchor.close, x.PrevEma, anchor.ema9, (((2 / (1 + @NDays)) * (anchor.close - x.PrevEma)) + x.PrevEma) AS NewEma FROM x JOIN anchor ON anchor.id = x.id + 1 -- `X` WALKS ITSELF )SELECT id, NewEmaFROM xORDER BY x.id;