Using “Update to a local variable” to calculate Grouped Running Totals

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-25 02:28:07

问题


As it appears to be the fasted method, I am trying to use the "Update to a local variable" method to calculate running totals in SQL. To add an extra layer to this, I am interested in being able to group the running totals, but I can't make sense of where to make the tweaks to my query to do this (or if it is even possible with this method). Any and all help will be appreciated.

Below is the code that I used to create my query, and the article that led me to this method in the first place. How can I modify the query to have the running total reset for every daycount

http://geekswithblogs.net/Rhames/archive/2008/10/28/calculating-running-totals-in-sql-server-2005---the-optimal.aspx

DECLARE @SalesTbl TABLE (DayCount smallint, Sales money, RunningTotal money)

DECLARE @RunningTotal money

SET @RunningTotal = 0

INSERT INTO @SalesTbl 
SELECT DayCount, Sales, null
FROM Sales
ORDER BY DayCount

UPDATE @SalesTbl
SET @RunningTotal = RunningTotal = @RunningTotal + Sales
FROM @SalesTbl

SELECT * FROM @SalesTbl

Thanks

Reilly


回答1:


The links in the comments allowed me to come up with the right coding. Below is how the update function needs to be modified to group by Day in the above example.

UPDATE @salestbl
SET @RunningTotal = RunningTotal = sales +
    CASE WHEN daycount=@lastday THEN @RunningTotal ELSE 0 END
   ,@lastday=daycount
FROM @salestbl


来源:https://stackoverflow.com/questions/12698479/using-update-to-a-local-variable-to-calculate-grouped-running-totals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!