Link to home
Start Free TrialLog in
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.
ASKER CERTIFIED SOLUTION
Avatar of Scott Pletcher
Scott Pletcher
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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...
Avatar of isames
isames

ASKER

Your query worked.

Would you explain it to me?
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.