SQL Server How to build zigzag subtraction

isr3a4wc  于 2023-10-15  发布在  其他
关注(0)|答案(1)|浏览(103)

I have interest payment table and I want to calculate this using subtraction by zigzag transaction in SQL at first I need to do this below

  1. sum (interest) = 3641.18
  2. from total interest (3641.18) - interest(998.96),date(2023-07-22) = outstanding(2642.22)
  3. then from outstanding(2642.22) - interest(941.69),date(2023-08-22) = outstanding(1700.53) until reach the bottom, date(2023-10-22) become outstanding = (0)
    | acct | date | interest | outstanding |
    | ------------ | ------------ | ------------ | ------------ |
    | 963 | 2023-07-22 | 998.96 | 2642.22 |
    | 963 | 2023-08-22 | 941.69 | 1700.53 |
    | 963 | 2223-09-22 | 881.69 | 818.84 |
    | 963 | 2223-10-22 | 818.84 | 0 |

I tried this query:

  1. Select fc.acct
  2. , date
  3. , interest
  4. ,SUM(case when DATEDIFF(yy,fc.date, tb.date) <= tb.tb1_start and DATEDIFF(yy,fc.date, tb.date) <= tb.tb1_end
  5. then fcalc.outs_interest - fc.interest else 0 end) AS oustanding
  6. from table fc
  7. INNER JOIN (Select acct, Sum(interest) outs_interest from table where GROUP BY acct)fcalc
  8. ON fcalc.acct = fc.acct
  9. ,dbo.axsp_get_timebands() tb
  10. where fc.acct = 963
  11. GROUP BY fc.acct, fc.date,fc.interest,fcalc.outs_interest

Output, that I got is like this from:

  1. total interest(3641.18) subtract per line
  2. total interest(3641.18) - interest(998.96),(date(2023-07-22)) = 2642.22
  3. total interest(3641.18) - interest(941.69),(date(2023-08-22)) = 2699.49 like that
acctdateinterestoutstanding
9632023-07-22998.962642.22
9632023-08-22941.692699.49
9632023-09-22881.692759.49
9632023-10-22818.842822.96

What I was expecting? is like below:
| acct | date | interest | outstanding |
| ------------ | ------------ | ------------ | ------------ |
| 963 | 2023-07-22 | 998.96 | 2642.22 |
| 963 | 2023-08-22 | 941.69 | 1700.53 |
| 963 | 2023-09-22 | 881.69 | 818.84 |
| 963 | 2023-10-22 | 818.84 | 0 |

knsnq2tg

knsnq2tg1#

Not sure what do you mean exactly by "zigzag subtraction", but you can achieve what you want using window function.

sum(interest) over () gives you the total interest which is 3641.18 .

And

sum(interest) over(order by date) gives you the running total of interest order by date

  1. select *,
  2. outstanding = sum(interest) over (partition by acct)
  3. - sum(interest) over (partition by acct
  4. order by date)
  5. from fc
  6. order by date

相关问题