重置总和

时间:2019-02-13 23:20:38

标签: python sql sql-server tsql count

我正在尝试根据数量创建机车车辆数量。每当有实际库存计数(TypeOfMovement = 3)时,该计数应重置。这应该适用于每个ArticleNo,并按日期分组。

我可以得到一个连续的存货盘点(图像中的行<123),然后在TypeOfMovement = 3(图像的行123)时取真实的存货量,但是该计数没有重置,它从实际存货之前开始计数(第124行的ResetRunningTotal应该为6293)。

该解决方案应在SSMS中运行。另外,也可以运行python解决方案。

到目前为止,我的查询是:

WITH a
AS
(SELECT
        DateOfMovement, Quantity, ArticleNo, TypeOfChange,
        CASE 
        WHEN TypeOfChange = 3 Then 0
        ELSE Quantity
        END AS RunningTotal
    FROM Stock_Table
    Group by DateOfMovement, Quantity, ArticleNo, TypeOfChange)
SELECT
    *
    ,CASE
        WHEN TypeOfChange= 3 THEN Quantity   
        ELSE Sum(Quantity) OVER(ORDER BY ArticleNo, DateOfMovement)
    END AS ResetRunningTotal
FROM a
WHEre ArticleNo = 9410
group by DateOfMovement, ArticleNo, Quantity, TypeOfChange, RunningTotal
order by DateOfMovement asc

结果表的图像是..

Image of result

1 个答案:

答案 0 :(得分:1)

好吧,所以您希望ArticleNo排序的每个DateOfMovement的运行总计,只要遇到TypeOfChange的值为3时就重置。

为此,您需要为每个运行总计创建一个grouping_id(Grp)。您可以使用计算组ID的CTE进行此操作,然后使用CTE结果进行运行总计:

with Groups as (
select st.*
     , sum(case TypeOfChange when 3 then 1 else 0 end)
       over (partition by ArticleNo order by DateOfMovement) Grp
  from Stock_Table st
)
select Groups.*
     , sum(Quantity) over (partition by ArticleNo, Grp order by DateOfMovement) RunningTotal
  from Groups
 order by ArticleNo, dateofmovement