Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Where clause needs to select last month's data

Author  Topic 

sqlobsessed
Starting Member

8 Posts

Posted - 2012-06-04 : 11:43:46
This automated report is pulling last month's data on the third of each month. Is there a more accurate way since this doesnt account for months with different amount of days?

where cb.DoNotDeliverDate between GETDATE()-33 and getdate()-3

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2012-06-04 : 12:29:18
Does this help?
SELECT *
FROM TableName
WHERE
DateColumn >= DATEADD(MONTH, DATEDIFF(MONTH, 0, SYSDATETIME()) - 1, 0)
AND DateColumn < DATEADD(MONTH, DATEDIFF(MONTH, 0, SYSDATETIME()), 0)

-- or

SELECT *
FROM TableName
WHERE
DateColumn >=DATEADD(MONTH, DATEDIFF(MONTH, '19000101', SYSDATETIME()) - 1, '19000101')
AND DateColumn < DATEADD(MONTH, DATEDIFF(MONTH, '19000101', SYSDATETIME()), '19000101')
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-06-04 : 12:30:35
quote:
Originally posted by sqlobsessed

This automated report is pulling last month's data on the third of each month. Is there a more accurate way since this doesnt account for months with different amount of days?

where cb.DoNotDeliverDate between GETDATE()-33 and getdate()-3


also see

http://visakhm.blogspot.com/2010/01/some-quick-tips-for-date-formating.html

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page

sqlobsessed
Starting Member

8 Posts

Posted - 2012-06-04 : 13:15:53
Thanks, both options work just the same. What exactly is 19000101??

Thanks visakh, i need to query your blog before posting questions!
Go to Top of Page

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2012-06-04 : 14:15:49
quote:
Originally posted by sqlobsessed

Thanks, both options work just the same. What exactly is 19000101??

19000101 (January 1st, 1900) is the same as day Zero (0). In this case it's just a base reference date.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-06-04 : 14:51:09
quote:
Originally posted by sqlobsessed

Thanks, both options work just the same. What exactly is 19000101??

Thanks visakh, i need to query your blog before posting questions!


no problem you're welcome

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -