Avatar of isames
isames
 asked on

SQL Query Past Due Query

I am trying to create a aging report using SQL.

I'm trying to grab the balance for all customers who had a invoice due in the previous month. So if it's March, then I want to show all the balances for invoices that were due in February.

This is what I came up with, but I keep getting 0 for the Customers that I know have balances in the month of February.



SELECT arar_cust_n, arar_due_date,
case
when arar_due_date = Month(DATEADD(mm, -1, GETDATE()))
then arar_balance
else 0
End as thirtydaypassed
from arar


Please help.
Microsoft SQL ServerMicrosoft SQL Server 2008SQL

Avatar of undefined
Last Comment
Scott Pletcher

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
Scott Pletcher

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Saurabh Singh Teotia

You can simply use this as well..

select arar_cust_n, arar_due_date,arar_balance
from arar
where month(arar_due_date) = month(getdate())-1 and year(arar_due_date)=year(getdate())

Open in new window


Saurabh...
isames

ASKER
Your query worked.

Would you explain it to me?
Scott Pletcher

Sure.  This part:
DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)
is a very efficient and common technique for getting the first day, at midnight, of the current month, for example, if run today it returns:
2015-03-01 00:00:00.000

Now, since you want the previous month only, I subtract 1 month from that to get the starting day of the previous month to be the lowest date:
>= DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) - 1, 0)

To make sure we don't count anything past last month, we use < (less than, not <=) of the first day of the current month:
< DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()), 0)

This technique means the code keeps working correctly even if the data type of the column being compared changes.  This code works accurately for any date/datetime data type, while the <= methods do NOT.

Similarly, if I wanted to get all data for 2014, I should code it this way:
column >= '20140101' AND column < '20150101'

Or, more generically:
column >= DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()) - 1, 0) AND
column < DATEADD(YEAR, DATEDIFF(YEAR, 0, GETDATE()), 0)

This approach is very flexible and very efficient.
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy