具有累积值的 SQL 更新表

SQL Update table with cumulative value(具有累积值的 SQL 更新表)
本文介绍了具有累积值的 SQL 更新表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有这张桌子:

Date  |StockCode|DaysMovement|OnHand
29-Jul|SC123    |30          |500
28-Jul|SC123    |15          |NULL
27-Jul|SC123    |0           |NULL
26-Jul|SC123    |4           |NULL
25-Jul|SC123    |-2          |NULL
24-Jul|SC123    |0           |NULL

只有第一行有 OnHand 值的原因是因为我可以从另一个表中获取它,该表存储任何股票代码的当前手头数量.

The reason only the top row has an OnHand value is because I can get this from another table that stores the current qty on hand for any stock code.

表中的其他记录取自另一个表,该表记录了任何给定日期的所有移动.

The other records in the table are taken from another table that logs all the movement for any given day.

我想更新上表,以便 OnHand 列根据前一条记录的库存和变动显示该行日期的 QtyOnHand,更新结束时如下所示:

I want to update the above table so that the OnHand column shows the QtyOnHand for that row's date based on the previous record's stock and movement, such that is looks like this at the end of the update:

Date  |StockCode|DaysMovement|OnHand
29-Jul|SC123    |30          |500
28-Jul|SC123    |15          |470
27-Jul|SC123    |0           |455
26-Jul|SC123    |4           |455
25-Jul|SC123    |-2          |451
24-Jul|SC123    |0           |453

我目前正在使用 CURSOR 实现这一目标.但性能真的很糟糕,超过了数千条记录.

I'm currently achieving this with a CURSOR. But performance really sucks over thousands of records.

是否有一些基于 SET 的 UPDATE 语句可以运行以达到相同的结果?

Is there some SET-based UPDATE statement I can run that will achieve the same result?

推荐答案

试试这个 (小提琴演示)

Try this (Fiddle demo)

DECLARE @Movement INT , @OnHandRunning INT  

;WITH CTE AS
(
    SELECT TOP 100 percent DaysMovement, OnHand 
    FROM Table1
    ORDER BY [StockCode], [Date] DESC
)
UPDATE CTE SET @OnHandRunning = OnHand = COALESCE(@OnHandRunning - @Movement, OnHand),
               @Movement = DaysMovement

更新:对于多个StockCodes,您可以修改上面的查询,如下所示(小提琴演示 2):

UPDATE: For multiple StockCodes you can modify above query like below (Fiddle demo 2):

DECLARE @Movement INT , @OnHandRunning INT, @StockCode VARCHAR(10) = '' 

;WITH CTE AS
(
    SELECT TOP 100 percent DaysMovement, OnHand, StockCode  
    FROM Table1
    ORDER BY [StockCode],[Date] DESC
)
UPDATE CTE SET @OnHandRunning = OnHand = 
       CASE WHEN @StockCode<> StockCode THEN OnHand ELSE @OnHandRunning - @Movement END,
       @Movement = DaysMovement,
       @StockCode = StockCode

这篇关于具有累积值的 SQL 更新表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

ibtmp1是非压缩的innodb临时表的独立表空间,通过innodb_temp_data_file_path参数指定文件的路径,文件名和大小,默认配置为ibtmp1:12M:autoextend,也就是说在文件系统磁盘足够的情况下,这个文件大小是可以无限增长的。 为了避免ibtmp1文件无止境的暴涨导致
SQL query to group by day(按天分组的 SQL 查询)
What does SQL clause quot;GROUP BY 1quot; mean?(SQL 子句“GROUP BY 1是什么意思?意思是?)
MySQL groupwise MAX() returns unexpected results(MySQL groupwise MAX() 返回意外结果)
MySQL SELECT most frequent by group(MySQL SELECT 按组最频繁)
Include missing months in Group By query(在 Group By 查询中包含缺失的月份)