如何在分类帐库存中获得累计金额

How to get cumulative sum in ledger stock

我想在总账库存中计算总和,但我不知道如何获得 请帮助我。

当前输出

LedgerID    ProductId   TType   ProductName  Credit   Debit    Stock    TDate
1              1        LGR     CAUSTIC        20      0       20   22/03/2018
12             1        GRN     CAUSTIC        10      0       30   26/03/2018
13             1        DA      CAUSTIC        0       15      30   26/03/2018
14             1        DA      CAUSTIC        0       15      30   26/03/2018
15             1        RM      CAUSTIC       10       0       40   26/03/2018

需要输出

LedgerID    ProductId   TType   ProductName  Credit   Debit    Stock    TDate
1              1        LGR     CAUSTIC        20      0       20   22/03/2018
12             1        GRN     CAUSTIC        10      0       30   26/03/2018
13             1        DA      CAUSTIC        0       15      15   26/03/2018
14             1        DA      CAUSTIC        0       15      00   26/03/2018
15             1        RM      CAUSTIC        10      0       10   26/03/2018

我的查询

select LedgerID,ProductId,TType,ProductName,
isnull(sum(case when DC = 'C' then Qty end),0) Credit,
ISNULL(sum(case when DC = 'D' then Qty end),0) Debit,
(select ISNULL(sum(case when DC = 'C' then Qty end),0) as Stock from LedgerMaster as b where b.LedgerID <= a.LedgerID and b.ProductId=a.ProductId) as Stock,
CONVERT(nvarchar(150), TDate,103) as TDate
from LedgerMaster as a  where ProductId=1
group by  LedgerID,ProductId,TType,ProductName, TDate 
order by ProductName desc, LedgerID asc

这可以通过 window 函数 SUM 轻松完成。我认为代码是 self-descriptive。逻辑是Credit的累计和减去Debit的累计和。

[Stock] = sum(credit) over (partition by productid order by TDate rows between unbounded preceding and current row)
        - sum(Debit) over (partition by productid order by TDate rows between unbounded preceding and current row)

另外,和差是差和,所以可以改写为:

[Stock] = sum(credit - debit) over (partition by productid order by TDate rows between unbounded preceding and current row)