我有一台ATM机,其中包含以下信息:
- --Date-----|--Withdraw---|---CashLoad
- 01/15/13--|----10----------|-------300
- 01/16/13--|----20
- 01/17/13--|----50
- 01/18/13--|---120
- 01/19/13--|----20----------|-------400
- 01/20/13--|----60
- 01/21/13--|----80
- 01/22/13--|----50
- 01/23/13--|----90----------|------300
我想计算该ATM的日终余额,此余额等于CashLoad - 每天的累计提款金额。如果ATM重新加载,则该过程重新开始
以下是我要找的内容:
- --Date------|--Withdraw---|------CashLoad---|--------EOD_Balance
- 01/15/13---|----10----------|-------300-----------|-----------290
- 01/16/13---|----20----------|-----------------------|-----------270
- 01/17/13---|----50----------|-----------------------|-----------220
- 01/18/13---|---120---------|------------------------|----------100
- 01/19/13---|----20----------|-------400-----------|-----------380
- 01/20/13---|----60----------|-----------------------|-----------320
- 01/21/13---|----80----------|-----------------------|-----------240
- 01/22/13---|----50----------|-----------------------|-----------190
- 01/23/13---|----90----------|-------300-----------|-----------210
这是我目前使用的查询:
select
tmp1.atminternalid, tmp1.date,
tmp1.CashLoad - tmp1.accum_disp as cashbalafterload
from mytable as tmp1 where SettlementDate = (select max(SettlementDate)
from DM_ADMIN.dbo.temptable1001 as tmp2
where tmp2.ATMInternalID = tmp1.atminternalid )
order by tmp1.atminternalid
如何更改查询以获取我要查找的结果?
答案 0 :(得分:0)
SQL Server 2008没有累积和函数。您可以使用相关子查询来解决此问题:
select atm.*,
(select sum(cashload) - sum(withdraw)
from atm atm2
where atm2.date <= atm.date
) as EOD_Balance
from atm;
编辑:
嗯,这确实改变了问题。您需要从上一次现金负担的日期开始总和:
select atm.*,
(select sum(cashload) - sum(withdraw)
from atm atm3
where atm3.date <= atm.date and
atm3.date >= CashLoadDate
) as EOD_Balance
from (select atm.*,
(select max(date)
from atm atm2
where atm2.date <= atm.date and
cashload > 0
) as CashLoadDate
from atm
) atm;