grahamie
grahamie

Reputation: 311

SQL - get last month data

I have been using this query to extract information from last month

SELECT * 
FROM Member
WHERE DATEPART(m, date_created) = DATEPART(m, DATEADD(m, -1, getdate()))

with the end of the year approaching, will this automatically pull Dec 2012 when i run it in Jan 2013 ?

Upvotes: 1

Views: 8004

Answers (3)

Yes, it will. DATEADD is a SQL internal function that adds to the full date, not just the selected part (day, month, year).

Upvotes: 1

podiluska
podiluska

Reputation: 51494

Yes, it will pull December data. But it will pull December data from any year, not just 2012

Upvotes: 1

techfun
techfun

Reputation: 953

Yes. your getdate() function will give the current date when the query is run. And you are adding -1 to the month and comparing month of date_created column and the last month. But I think you should also do comparison of year. You should add two conditions month and year both.

Upvotes: 1

Related Questions