Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Recursive sql

$
0
0

I need help please.

I have a table with payments. I need to check for each idno if he has payments for a certain year that exceeds the total amount allowed. In my example the total amount allowed for each month of year 2006 is 2000,00.

I need to go each month and check the total.

For month 1 payments<2000 so I continue to month 2 and in month 3 I see that payments>2000.

I have to show in my output month 3,the maximum amount of payments allowed till that month so it's 2000*3, sum (payments) where month in (1,2,3) and also show the result for payments for month 3 less 2000.

I continue to check the next month. Month 4 has payments over 2000 so I show this month also.

However, since I already checked the previous months I don't need to calculate values from previous months. Only show the payments for that month.

Month 5 is fine but month 6 again has payments>2000.

So I show month 6, max amount of payments allowed is now 2000*2, sum (payments) where month in (5,6)

create table #Installments (idno int, payYear int, payMonth int,Payments decimal (10,2))

insert into #Installments

select 34576,2006,  1, 1704.53 union

select 34576,2006,2,1683.18         union

select  34576,2006,3, 3000.00       union

select 34576,2006,4,5000.00         union

select 34576,2006,5,1174.24         union

select 34576,2006,6,2540.62        

select *,case when payments>2000.00 then 1 else 0 end from #Installments

idno

payYear

payMonth

Payments

Exceeds  2000.00

34576

2006

1

1704.53

N

34576

2006

2

1683.18

N

34576

2006

3

3000.00

Y

34576

2006

4

5000.00

Y

34576

2006

5

1174.24

N

34576

2006

6

2540.62

Y

 

OUTPUT

 select 3 as payMonth, 2000.00*3 MaxPaymentsAllowedTillMonth,sum (Payments) TotalPaymentsTillMonth ,3000.00 TotalforMonth,3000.00-2000.00 DeviationAmount

 from #Installments

 where payMonth <4

 union

  select 4 as payMonth, 2000.00*1 MaxPaymentsAllowedTillMonth,sum (Payments) TotalPaymentsTillMonth,5000.00 TotalforMonth,5000.00-2000.00 DeviationAmount

 from #Installments

 where payMonth in (4)

 union

 select 6 as payMonth, 2000.00*2 MaxPaymentsAllowedTillMonth,sum (Payments) TotalPaymentsTillMonth,2540.62 TotalforMonth,4000.00-2000.00 DeviationAmount

 from #Installments

 where payMonth in (5,6)

payMonth

MaxPaymentsAllowedTillMonth

TotalPaymentsTillMonth

TotalforMonth

OverAmount

3

6000.00

6387.71

3000.00

1000.00

4

2000.00

5000.00

5000.00

3000.00

6

4000.00

3714.86

2540.62

2000.00




Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>