【问题标题】:How to get cumulative sum in ledger stock如何获得分类帐中的累积金额
【发布时间】:2018-09-05 10:21:52
【问题描述】:

我想在分类帐中累积总和,但我不知道如何获得 请帮帮我。

电流输出

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

【问题讨论】:

    标签: sql sql-server sql-server-2008 sql-server-2005 sql-server-2012


    【解决方案1】:

    这可以通过窗口函数SUM 轻松完成。我认为代码是自我描述的。逻辑是从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)
    

    【讨论】:

    • 我使用 where ProductId=1 所以输出完美,但我没用 where 所以输出不完美
    • 我想要产品明智的累积
    • 我不知道你在说什么。
    • 您的答案仅适用于一种产品,例如 where productid=1 我想在没有 where 条件的情况下适用于所有产品
    • @DenishParvadia 你没有提到它应该被分区......更新的解决方案应该可以工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-11
    • 1970-01-01
    • 2012-05-25
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    相关资源
    最近更新 更多