Thursday, March 17, 2016

Aging Report using SQL-Server



declare @AdvanceDate datetime
set @AdvanceDate='02/29/2016'
--select DATEADD(DD,-90,@AdvanceDate)

select
ST, LOB,
case when  cast([Advance Date] as datetime)<DATEADD(DD,0,@AdvanceDate) and cast([Advance Date] as datetime)>=DATEADD(DD,-30,@AdvanceDate) then [Current Balance] else 0 end [Age30],
case when  cast([Advance Date] as datetime)<DATEADD(DD,-30,@AdvanceDate) and cast([Advance Date] as datetime)>=DATEADD(DD,-60,@AdvanceDate) then [Current Balance] else 0 end [Age60],
case when  cast([Advance Date] as datetime)<DATEADD(DD,-60,@AdvanceDate) and cast([Advance Date] as datetime)>=DATEADD(DD,-90,@AdvanceDate) then [Current Balance] else 0 end [Age90],
case when  cast([Advance Date] as datetime)<DATEADD(DD,-90,@AdvanceDate) and cast([Advance Date] as datetime)>=DATEADD(DD,-120,@AdvanceDate) then [Current Balance] else 0 end [Age120],
case when  cast([Advance Date] as datetime)<DATEADD(DD,-120,@AdvanceDate) and cast([Advance Date] as datetime)>=DATEADD(DD,-150,@AdvanceDate) then [Current Balance] else 0 end [Age150],
case when  cast([Advance Date] as datetime)<DATEADD(DD,-150,@AdvanceDate) and cast([Advance Date] as datetime)>=DATEADD(DD,-180,@AdvanceDate) then [Current Balance] else 0 end [Age180],
case when  cast([Advance Date] as datetime)<DATEADD(DD,-180,@AdvanceDate) and cast([Advance Date] as datetime)>=DATEADD(DD,-210,@AdvanceDate) then [Current Balance] else 0 end [Age210],
case when  cast([Advance Date] as datetime)<DATEADD(DD,-210,@AdvanceDate) then [Current Balance] else 0 end [Age>210]  into #temp11
--cast([Advance Date] as datetime)[Advance Date]
from #temp1 where  cast([Advance Date] as datetime)<=@AdvanceDate

select
ST,LOB,sum(Age30)Age30,    sum(Age60)Age60,     sum(Age90)Age90,     sum(Age120)Age120,       sum(Age150)Age150,   sum(Age180)Age180, sum(Age210)Age210,    sum([Age>210])[Age>210]
from  #temp11 group by st,[lob]






No comments: