question

technette avatar image
technette asked

Selecting a date Range

I have a column with the following date format: 2002-03-25 00:00:00.000 In my query, I want to specify a date range for the past 3 years. How do I do that?
date-range
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

1 Answer

·
Grant Fritchey avatar image
Grant Fritchey answered
Two ways immediately come to mind: ...WHERE MyDate > DATEADD(year,-3,GETDATE()) --or ...WHERE MyDate DATEADD(year,-3,GETDATE()) and BETWEEN GETDATE() Either will work. Probably the first is easier. The second allows for the idea of controlling the range more directly.
6 comments
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

Grant Fritchey avatar image Grant Fritchey ♦♦ commented ·
Fixed it so it looks right.
1 Like 1 ·
technette avatar image technette commented ·
Thank you for responding Grant! The between query doesn't return data... maybe because the current date may not work if there is not data in this table for the current date. The first query returns data but I'm still getting the following: 2049-12-31 00:00:00.000
0 Likes 0 ·
technette avatar image technette commented ·
It worked with I used: DATEADD(year,+3,GETDATE()) Thank you!
0 Likes 0 ·
Martin Schoombee avatar image Martin Schoombee commented ·
Using dateadd(year,+3,getdate()) is not correct...it will give you the data for the next 3 years and not the past 3 years. To get Grant's 2nd suggestion to work, switch the 2 predicates around. The "between" operator needs the lower limit to be first, i.e. ...between dateadd(year,-3,getdate()) and getdate()
0 Likes 0 ·
Grant Fritchey avatar image Grant Fritchey ♦♦ commented ·
Ouch. Sorry about that. Thanks for the correction @Martin
0 Likes 0 ·
Show more comments

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.