Tuesday, February 21, 2012

Returning last months data

I'm running a query in a reporting program which returns all fields for a certain date (using SQL). One of the queries was to find tuples that had a date that equalled yesterday. so to get the correct results just queried date >= sysdate-1 and date < sysdate.

I now need to try and get it to return records for all the previous month. This is run every month so I can't just put in date >= 01-AUG-2005 and date < 01-SEP-2005. Any ideas how i could automate this using sysdate so i dont have to change the fields manually everytime?

Thanks in advance.

last day of prior month:
dateadd(ms,-3,DATEADD(mm, DATEDIFF(mm,0,getdate()), 0))
first day of prior month:
dateadd(mm,DATEDIFF(mm,0,DATEADD(mm,-0-DATEPART(day,0),getdate())),0)

Hope this helps,
Josh|||What about this one?

SELECT *
FROM your_table
WHERE YEAR(date) = YEAR(GETDATE())
AND MONTH(date) = MONTH(GETDATE()) - 1|||That sounds nearly about right but bascially im trying to compare it with a variable.

i.e:

SELECT *
FROM table
WHERE TO_CHAR(var1, 'YYYY/MM') >= '2005/08'
AND TO_CHAR(var1, 'YYYY/MM') < '2005/09'

What i'm wanting to automate is the 2005/08 and the 2005/09, so i can compare value in that format.

No comments:

Post a Comment