Tuesday, March 27, 2012

Date query

I have a query which finds records that are >= todays date. The user has
requested that I should display the records a year back from todays date in
addition to >= todays date. I'm using the following "where" clause.
WHERE (ED_COURSE_CL_1.CLASS_DATE >= GETDATE())
How can I acheive this.
ThanksLook up DATEADD function in SQL Server Books Online.
The various arguments of this function should allow you to do generate an
expression that is equal to a date last year.
--
Anith|||Here are a few date calculations that will give you a good idea of selecting
date ranges. Note that these calculations include entire days. In your
example using GETDATE cuts at the current time of the day which can leave
some rows for the current day out.
-- select past year including today and the day a year ago
-- if today is Feb 20, 2007, then it will include from Feb 20, 2006 to Feb
20, 2007
WHERE ED_COURSE_CL_1.CLASS_DATE < DATEDIFF(day, 0, getdate() + 1)
AND ED_COURSE_CL_1.CLASS_DATE >= DATEDIFF(day, 0, DATEADD(year, -1,
getdate()))
-- select past year excluding today and the day a year ago
-- if today is Feb 20, 2007, then it will include from Feb 21, 2006 to Feb
19, 2007
WHERE ED_COURSE_CL_1.CLASS_DATE < DATEDIFF(day, 0, getdate())
AND ED_COURSE_CL_1.CLASS_DATE >= DATEDIFF(day, -1, DATEADD(year, -1,
getdate()))
-- select past year excluding today and including the day a year ago
-- if today is Feb 20, 2007, then it will include from Feb 20, 2006 to Feb
19, 2007
WHERE ED_COURSE_CL_1.CLASS_DATE < DATEDIFF(day, 0, getdate())
AND ED_COURSE_CL_1.CLASS_DATE >= DATEDIFF(day, 0, DATEADD(year, -1,
getdate()))
-- select today and all future dates
WHERE ED_COURSE_CL_1.CLASS_DATE >= DATEDIFF(day, 0, getdate())
Regards,
Plamen Ratchev
http://www.SQLStudio.com

No comments:

Post a Comment