August 19, 2004 at 6:45 am
Hi,
I am trying to pull in all data from a startdate field but I only want to see the data up to the previous month. For an example today is 8/19/2004 I want to see all the records before 8/01/2004. I have tried several different things and nothing is quite working correctly. Thanks for any help you can give.
JW
August 19, 2004 at 7:27 am
Will this work?
WHERE MONTH(mydate) < MONTH(GETDATE())
August 19, 2004 at 7:51 am
This gives me this years data <08/01/2004 but for the data in 2003 it doesn't give me any months past 07/31/2003 so I don't get 8/2003, 9/2003, 10/2003, 11/2003, 12/2003 data and the same for the year 2002.
August 19, 2004 at 8:02 am
I guess that is true. What about this?
WHERE mydate < cast(cast(month(Getdate())as char) + '/01/' + cast(year(getdate())as char) AS SMALLDATETIME)
There might be a better way of doing this.
August 19, 2004 at 10:00 am
Thank You, Thank You, Thank You......
That worked perfectly!!!!!!
August 20, 2004 at 5:59 am
Neater, and probably faster, would be :
WHERE StartDate <= DATEADD(d, -DAY(GETDATE()), GETDATE())
August 20, 2004 at 7:33 am
Another way (more clear, but probably slower), could be:
WHERE MONTH(MyDate)<MONTH(GetDate()) AND YEAR(MyDate)=YEAR(GetDate()) OR YEAR(MyDate)<YEAR(GetDate())
I think Stewart's solution is the best, but it works correctly only if there is no time portion in the column (indeed, usually, there is only the date portion).
Razvan
August 20, 2004 at 7:43 am
Good point about time - careless of me. If this is a concern, you need :
WHERE StartDate < DATEADD(d, DATEDIFF(d, 0, DATEADD(d, 1 - DAY(GETDATE()), GETDATE())), 0)
This calculates the number of days from SQL Server's base date and then adds that number of days to the base date. Note that we are now looking for dates LESS THAN the 1st of the current month.
This construction is a general way of stripping the time from a datetime value.
August 20, 2004 at 8:05 am
Thanks for the variations! I will have to remember the negative datediff usage.
-A
August 20, 2004 at 9:11 am
Stewart, here is a better (easier) way:
WHERE StartDate < DATEADD(m, DATEDIFF(m, 0, GETDATE()), 0)
Razvan
August 20, 2004 at 9:18 am
Good thinking. You're quite right. Many thanks.
August 20, 2004 at 9:41 am
Thank you all very much for all the code examples. I was struggling with this for a few weeks. Now I can have a relaxing weekend. Hopefully you will do the same.
Viewing 12 posts - 1 through 11 (of 11 total)
You must be logged in to reply to this topic. Login to reply