earwig75
asked on
How to query date ranges with SQL
Hello, can some help me understand how to query the below date ranges with MS SQL?
The field is called "myDate" . So if Today's date is 11/16/16.....
I need to get records that were created from midnight of the current day, through right now. (11/16/16 12AM - now)
Next, I need to get records created from midnight of the previous day, to records created at midnight of the current day. (11/15/16 12am - 11/15/16 23:59pm)
Next, I need to get records created between 2 days ago and 14 days ago. (11/2/16 12am - 11/13/16 23:59pm)
I know this is confusing, but can someone assist? Thank you.
The field is called "myDate" . So if Today's date is 11/16/16.....
I need to get records that were created from midnight of the current day, through right now. (11/16/16 12AM - now)
Next, I need to get records created from midnight of the previous day, to records created at midnight of the current day. (11/15/16 12am - 11/15/16 23:59pm)
Next, I need to get records created between 2 days ago and 14 days ago. (11/2/16 12am - 11/13/16 23:59pm)
I know this is confusing, but can someone assist? Thank you.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Btw, the above only works for MSSQL 2012 and superior.
ASKER
Thank you. I have one more question if you don't mind, because I am confused about how this works. If i needed the records for 15-30 Days, would I use:
WHERE myDate >= CAST(GETDATE()-30 AS DATE) AND myDate < CAST(GETDATE()-14 AS DATE)
?
WHERE myDate >= CAST(GETDATE()-30 AS DATE) AND myDate < CAST(GETDATE()-14 AS DATE)
?
Yes, you got it ;)
ASKER
Perfect, thank you.
Btw, the above only works for MSSQL 2012 and superior.
Good approach. FWIW, should work in 2008+. IIRC, that is when data type DATE was added.