user1661868
user1661868

Reputation: 31

How to select last three month all dates in SQL Server

I want to select all last 3 month dates from the table in SQL Server.

Data is like this:

Sunday 20-05-2012
Sunday 27-05-2012
Sunday 10-06-2012
Sunday 24-06-2012
Sunday 08-07-2012
Sunday 22-07-2012
Sunday 12-08-2012
Sunday 19-08-2012
Sunday 09-09-2012
Sunday 16-09-2012

Upvotes: 0

Views: 10858

Answers (2)

Xordal
Xordal

Reputation: 1369

Saving date column as varchar with day of week - bad idea. You can't write faster query, because you must convert all of time your field for using it in where clause. Also your query can't use indexes of date_column and each query will be use scan index.

With datetime column, query should be:

select date_column
  from table_name
 where date_column between dateadd(m, -3, getdate()) and getdate()

Upvotes: 4

Seasoned
Seasoned

Reputation: 1059

Try using this query:

select date_column from table_name
where datepart(m,date_column) > datepart(m,getdate())-3 and datepart(yy,date_column) >= datepart(yy,getdate())

Upvotes: 1

Related Questions