0

以下の情報を持つ ATM マシンが 1 台あります。

-   --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 の 1 日の終わりの残高を計算したいのですが、この残高は、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

探している結果が得られるようにクエリを変更するにはどうすればよいですか?

4

1 に答える 1

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;
于 2014-01-22T22:20:49.227 に答える