我想在分类帐库存中累积总和,但我不知道如何获得 请帮帮我。
当前输出
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
答案 0 :(得分:4)
使用窗口函数SUM
可以轻松完成此操作。我认为代码是自我描述的。逻辑是从累计和Debit
中减去Credit
的累计和。
[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)