Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Update SQL Table Column in same table with Running Total

I have three fields in my table called SCURVE fields are id, DailyPlanned and CumPlanned
I have inserted around 300 values into the DailyPlanned field, I am trying to Update the CumPlanned with a running total as the ID increases. I have tried several methods but this does give me the running total

SELECT SUM (DailyPlanned) OVER (ORDER BY Id) AS RunningTotal FROM SCURVE

I tried using the following to update the value of CumPlanned that has the same ID with calculatyed running total, something like Update

UPDATE SCURVE SET CumPlanned = (Select SUM (DailyPlanned) OVER (ORDER BY Id) AS RunningTotal 
    From SCURVE S 
    Where S.id=SCURVE.id)

The other suggestion on stack was here
LINK

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

No luck with it either

WITH SCURVE AS
 (SELECT id, DailyPlanned,
         Sum(DailyPlanned) OVER (partition BY id) AS RunningTotal 
  FROM SCURVE
 ) UPDATE SCURVE SET CumPlanned = RunningTotal

My Table:

CREATE TABLE [dbo].[SCURVE](
[id] [int] IDENTITY(1,1) NOT NULL,
[CumPlanned] [decimal](3, 0) NULL,
[DailyPlanned] [decimal](3, 0) NULL) 
ON [PRIMARY]

>Solution :

I suggest not proceeding with this update operation, as the rolling sum is derived data and probably should always be computed on the fly. That being said, if you really must do this, an updatable CTE should work:

WITH cte AS (
    SELECT CumPlanned, SUM(DailyPlanned) OVER (ORDER BY Id) AS RunningTotal
    FROM SCURVE
)

UPDATE cte
SET CumPlanned = RunningTotal;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading