Click here to Skip to main content
15,034,331 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi,
I need to write a select query to get last two months data from a table ,
I am using sql server 2005. I am getting right data but if year changes then how to get data?

Please find below query :-

SQL
select
*,comments
from educator_call_dtls where eid=@eid and
(month(call_date) = month(getdate())-1 or month(call_date) = month(getdate())) order by call_id desc
Posted

Use DateAdd()[^] function.
SQL
select *,comments
from educator_call_dtls
where eid=@eid and [call_date] BETWEEN DATEADD(mm,-2,GETDATE()) AND GETDATE()
order by call_id desc
   
v2
Comments
Sweetynewb 12-Feb-13 3:58am
   
It is giving all months data not last two..
Maciej Los 12-Feb-13 4:06am
   
Sorry, you're right. See my answer after update.
Sweetynewb 12-Feb-13 4:26am
   
ok. yes this is working now.
Maciej Los 12-Feb-13 5:16am
   
If my answer was helpful, please, rate it.
You can also try datediff.
SQL
select
*,comments
from educator_call_dtls where eid=@eid and
DATEDIFF(month, call_date, getdate()) < 2
order by call_id desc
   
Comments
Sweetynewb 12-Feb-13 4:07am
   
Superb.... got exactly what i want, even it does not need to check for year

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900