我需要一些关于计算跑步余额的帮助。下面是表格D009040
的输出。
LBrCode MainAcctId EntryDate SetNo DrCr FcyTrnAmt
15 20060000000000030000000100000000 4/27/2015 11332 C 200
15 20060000000000030000000100000000 5/7/2015 8050 D 500
15 20060000000000030000000100000000 5/18/2015 11270 D 500
15 20060000000000030000000100000000 6/1/2015 13009 C 500
15 20060000000000030000000100000000 6/28/2015 81916 C 22.17
15 20060000000000030000000100000000 7/20/2015 11196 C 500
15 20060000000000030000000100000000 4/20/2015 11127 C 1000
15 20060000000000030000000100000000 4/28/2015 88017 C 6.37
15 20060000000000030000000100000000 5/11/2015 11176 D 500
15 20060000000000030000000100000000 5/25/2015 11201 D 300
15 20060000000000030000000100000000 6/15/2015 11075 C 500
15 20060000000000030000000100000000 7/6/2015 11069 C 500
15 20060000000000030000000100000000 7/28/2015 97098 C 32.43
15 20060000000000030000000100000000 4/16/2015 1019 C 3000
15 20060000000000030000000100000000 4/27/2015 11333 D 200
15 20060000000000030000000100000000 5/11/2015 11175 C 500
15 20060000000000030000000100000000 5/25/2015 11200 C 500
15 20060000000000030000000100000000 6/8/2015 10700 C 500
15 20060000000000030000000100000000 6/29/2015 11464 C 500
15 20060000000000030000000100000000 7/27/2015 10701 C 500
15 20060000000000030000000100000000 4/20/2015 11128 D 1000
15 20060000000000030000000100000000 5/7/2015 8049 C 500
15 20060000000000030000000100000000 5/18/2015 11269 C 500
15 20060000000000030000000100000000 5/28/2015 82065 C 14.86
15 20060000000000030000000100000000 6/22/2015 11101 C 500
15 20060000000000030000000100000000 7/13/2015 11401 C 500
我想计算借方和贷方分录,并获得每个日期的运行余额。我使用以下查询。
SELECT CM.LBrCode, CM.MainAcctId, CM.EntryDate,
sum(CASE WHEN CM.DrCr='C' THEN CM.FcyTrnAmt
WHEN CM.DrCr='D' THEN CM.FcyTrnAmt * -1 END)
OVER (PARTITION BY CM.MainAcctId ORDER BY CM.SetNo) As Amount,
sum(CASE WHEN CM.DrCr='C' THEN CM.FcyTrnAmt
WHEN CM.DrCr='D' THEN CM.FcyTrnAmt * -1 END)
OVER (PARTITION BY CM.MainAcctId ORDER BY CM.SetNo) As Amount
FROM D009040 CM
它会计算运行余额,但如果同一天有两笔交易,则会计算并显示两笔余额。我的要求是,如果同一天有两笔交易,那么请借记或贷记,并显示该日期的单一最新余额。
我对如何做到这一点有任何想法?
答案 0 :(得分:0)
可能是这样的:
; WITH Base AS
(
SELECT MIN(CM.LBrCode) LBrCode,
CM.MainAcctId,
CM.EntryDate,
MIN(CM.SetNo) SetNo,
SUM(CASE
WHEN CM.DrCr = 'C' THEN CM.FcyTrnAmt
WHEN CM.DrCr = 'D' THEN CM.FcyTrnAmt * -1
END) FcyTrnAmt
FROM #D009040 CM
GROUP BY CM.MainAcctId, CM.EntryDate
)
SELECT B.LBrCode,
B.MainAcctId,
B.EntryDate,
B.FcyTrnAmt,
SUM(B.FcyTrnAmt) OVER (PARTITION BY B.MainAcctId ORDER BY B.SetNo) Balance
FROM Base B
我首先在Base
计算当天的总动作,然后在第二个SELECT
中计算总计。请注意,我不太喜欢第一个SELECT
按EntryDate
分组的事实(因此给予"日期"最重要的操作),而第二个SELECT
是ORDER BY
SetNo
,这是因为第一个操作可以/会使某些SetNo
"消失" (MIN(CM.SetNo)
)