Pergunta

I have one ATM machine that has information below:

-   --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

I want to calculate the end-of-day balance for that ATM, this balance equals to the CashLoad - accumulated Withdraw amounts of each day. If the ATM is reloaded, the process starts over again

Here is what I'm looking for:

-   --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

This is the query I am currently using:

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

How do I change my query to get the results I am looking for?

Foi útil?

Solução

SQL Server 2008 doesn't have a cumulative sum function. You can solve this with a correlated subquery:

select atm.*,
       (select sum(cashload) - sum(withdraw)
        from atm atm2
        where atm2.date <= atm.date
       ) as EOD_Balance
from atm;

EDIT:

Well, that does change the problem. You need to sum from the date of the previous cash load:

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;
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top