Not sure if this will work for older versions of SQL, but...
I figured out that the following works great if you want to be precise about returning results in a "calendar day" fashion for any "number of days ago" (probably works for months and years too), regardless of what time, year, month, or day of the month you are running your query on while being exact about what is and isn't included in your results...
For example, let's say you want to return "Total Logins in Past 7 Days" but today is the 4th day of the month, or you want the "past 7 calendar days" without including some chunk of today, day 8, or cutting day 7 in half. When using day(), dateadd(), and/or getdate()
in various combinations, you may encounter issues depending on what time/day/month/year you run your query as this will typically affect your results if using =, >, <, >=, <=, in
operators...
So I found the following is one way to get around that:
"Yesterday's Logins"
select count(Id) as 'Logged in Yesterday'
from dbo.Users
where LastLoggedIn between dateadd(day, -1, convert(date, getdate()))
and dateadd(day, -0, convert(date, getdate()))
"Logins for Past 7 Days" (without including some chunk of today or day 8)
select count(Id) as 'Logins for Past 7 Days'
from dbo.Users
where LastLoggedIn between dateadd(day, -7, convert(date, getdate()))
and dateadd(day, -0, convert(date, getdate()))
and so on...
You can pretty much adjust the two values being subtracted for anything you want and it will always give you a calendar-day level of precision.
Please let me know if I can improve this answer as I just fiddled with it until I got the results I wanted, so this may or may not be the best way to go about it.
Submission_date
. Edit: it's in the title but we should confirm it is not of typeDate
:) – EvilmindedDATE()
built-in function in SQL Server ... he needs to do aCAST(... AS DATE)
– Maxa