SQL query to start from hour 12:00 am - sql

I have a date column like this 7/24/2017 and when I write the below where clause I get results from hour 7/24/2017 1:00:00.000 AM. I need to get this from 7/24/2017 12:00:00.000 AM. How should this where clause me modified. Please check the following code
Date>= DATEADD(day, -1, convert(date, GETDATE())) and
Date< DATEADD(day, +0, convert(date, GETDATE()))

There doesn't appear to be anything wrong with your code. Are you certain your data contains any times before 1am? Are you certain you appreciate how your SQLServer will format those times/represent them to you?
See this SQLFIDDLE: http://sqlfiddle.com/#!6/047cc/11
Optimisations: you don't need to dateadd a value of 0. You can also subtract 1.0 from a date to get the day earlier and it's a bit less wordy than DATEADD. It works because internally dates are represented as floating point numbers of the number of days since a point in time:
[Date] >= convert(date, GETDATE() -1.0) and
[Date] < convert(date, GETDATE())

Related

Auto Update Date for Given range in SQL

I have a SQL query by which I have to extract data from the server but every time I have to change the date range
where date(usf.created_date) BETWEEN '2022-04-01 00:00:00' and '2022-04-30 23:59:59'
but I want to get this range auto-update from today 30 days back.
I have tried the casting method Cast(GETDATE() as smalldatetime) but it shows an error in the same.
Assuming based on GETDATE() that this is SQL Server, you either want:
-- get everything going back exactly 30 days from this moment
WHERE usf.created_date >= DATEADD(DAY, -30, GETDATE());
Or:
-- get everything going back 30 days from this morning at midnight
WHERE usf.created_date >= DATEADD(DAY, -30, CONVERT(date, GETDATE()));

Rounding DateTime in SQL

I have DateTime data in a MS SQL database with the following format:
2020-05-07 22:35:00
I am trying to create a query that only captures data from the last 24 hours of operations. However, our operations KPIs are measured from 6AM-6AM. I would like to round the date based on time. Anything before 6AM will be counted as the day before.
2020-05-07 05:45:00 -> 2020-05-06 (Before 6AM)
2020-05-07 06:30:00 -> 2020-05-07 (After 6AM)
So far I have been successful in pulling the previous days activity, but am struggling to shift the timeframe to round down anything before 6AM
SELECT
end_date
FROM data sint
WHERE sint.end_date >= dateadd(day,datediff(day,1,GETDATE()),0)
AND sint.end_date < dateadd(day,datediff(day,0,GETDATE()),0)
You can add six hours to the current date (without the time) for the comparison:
where int.end_date < dateadd(hour, 6, convert(datetime, convert(date, getdate()))) and
int.end_date >= dateadd(hour, 6 - 24, convert(datetime, convert(date, getdate())))
Note that the conversion to date removes the time component.
first get the time part. Compare the time part with 6AM and run your expression.
In below code the time part is compared with the date '1900-01-01 06:00:00' which is 6AM in default date format.
select
case when cast(date as time(0)) < '1900-01-01 06:00:00'
then cast(date - 1 as date)
else cast(date as date)
end as newdate
from temp_date;
I would do the same as Gordon only the opposite side.
I would subtract 6 hours from end_date and then compare.
where convert(date, dateadd(hour, -6, int.end_date)) = convert(date, getdate())
Though this method might not work well if you're actually using getdate(). It will return nothing if it is ran between midnight and 6 am (unless you have future dates).

SQL Date only in Where clause [duplicate]

If I have a date value like 2010-03-01 17:34:12.018
What is the most efficient way to turn this into 2010-03-01 00:00:00.000?
As a secondary question, what is the best way to emulate Oracle's TRUNC function, which will allow you to truncate at Year, Quarter, Month, Week, Day, Hour, Minute, and Second boundaries?
To round to the nearest whole day, there are three approaches in wide use. The first one uses datediff to find the number of days since the 0 datetime. The 0 datetime corresponds to the 1st of January, 1900. By adding the day difference to the start date, you've rounded to a whole day;
select dateadd(d, 0, datediff(d, 0, getdate()))
The second method is text based: it truncates the text description with varchar(10), leaving only the date part:
select convert(varchar(10),getdate(),111)
The third method uses the fact that a datetime is really a floating point representing the number of days since 1900. So by rounding it to a whole number, for example using floor, you get the start of the day:
select cast(floor(cast(getdate() as float)) as datetime)
To answer your second question, the start of the week is trickier. One way is to subtract the day-of-the-week:
select dateadd(dd, 1 - datepart(dw, getdate()), getdate())
This returns a time part too, so you'd have to combine it with one of the time-stripping methods to get to the first date. For example, with #start_of_day as a variable for readability:
declare #start_of_day datetime
set #start_of_day = cast(floor(cast(getdate() as float)) as datetime)
select dateadd(dd, 1 - datepart(dw, #start_of_day), #start_of_day)
The start of the year, month, hour and minute still work with the "difference since 1900" approach:
select dateadd(yy, datediff(yy, 0, getdate()), 0)
select dateadd(m, datediff(m, 0, getdate()), 0)
select dateadd(hh, datediff(hh, 0, getdate()), 0)
select dateadd(mi, datediff(mi, 0, getdate()), 0)
Rounding by second requires a different approach, since the number of seconds since 0 gives an overflow. One way around that is using the start of the day, instead of 1900, as a reference date:
declare #start_of_day datetime
set #start_of_day = cast(floor(cast(getdate() as float)) as datetime)
select dateadd(s, datediff(s, #start_of_day, getdate()), #start_of_day)
To round by 5 minutes, adjust the minute rounding method. Take the quotient of the minute difference, for example using /5*5:
select dateadd(mi, datediff(mi,0,getdate())/5*5, 0)
This works for quarters and half hours as well.
If you are using SQL Server 2008+, you can use the Date datatype like this:
select cast(getdate() as date)
If you still need your value to be a DateTime datatype, you can do this:
select cast(cast(getdate() as date) as datetime)
A method that should work on all versions of SQL Server is:
select cast(floor(cast(getdate() as float)) as datetime)
Try:
SELECT DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)
UPDATE: answer on the second question:
for years you could use a little bit modified version of my answer:
SELECT DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0)
for quarter:
SELECT DATEADD(qq, DATEDIFF(qq, 0, GETDATE()), 0)
and so on.
I checked, up to minutes - it's OK. But on seconds I've got an overflow message:
Difference of two datetime columns
caused overflow at runtime.
One more update: take a look to the following answer to the same question
This is late, but will produce the exact results requested in the post. I also feel it is much more intuitive than using dateadd, but that is my preference.
declare #SomeDate datetime = '2010-03-01 17:34:12.018'
SELECT
DATEFROMPARTS(
YEAR(#SomeDate)
,MONTH(#SomeDate)
,'01'
) AS CUR_DATE_FROM_PARTS
,DATETIMEFROMPARTS(
YEAR(#SomeDate)
,MONTH(#SomeDate)
,'01' --DAY(#SomeDate)
,'00' --DATEPART(HOUR,#SomeDate)
,'00' --DATEPART(MINUTE,#SomeDate)
,'00' --DATEPART(SECOND,#SomeDate)
,'00' --DATEPART(MILLISECOND,#SomeDate)
) AS CUR_DATETIME_FROM_PARTS
,#SomeDate AS CUR_DATETIME
,YEAR(#SomeDate) AS CUR_YEAR
,MONTH(#SomeDate) AS CUR_MONTH
,DAY(#SomeDate) AS CUR_DAY
,DATEPART(HOUR,#SomeDate) AS CUR_HOUR
,DATEPART(MINUTE,#SomeDate) AS CUR_MINUTE
,DATEPART(SECOND,#SomeDate) AS CUR_SECOND
,DATEPART(MILLISECOND,#SomeDate) AS CUR_MILLISECOND
FROM Your_Table
Truncated Date: 2010-03-01
Truncated DateTime: 2010-03-01 00:00:00.000
DateTime: 2010-03-01 17:34:12.017
Not sure if this is the most efficient, but I like the simplicity in using the following where #SomeDate is your field.
Concat(Year(#SomeDate), '-', Month(#SomeDate), '-', '01')
If you want to truncate a date to the start of the week in a way that is independent of SET DATEFIRST you can:
--change a date backwards to nearest Monday
DATEADD(DAY, (DATEPART(dw, '2001-01-01') - DATEPART(dw, YOUR_COLUMN)-7)%7, YOUR_COLUMN)
Breaking this down:
DATEPART(dw, '2001-01-01') - DATEPART(dw, YOUR_COLUMN): the dw of a known Monday (2001-01-01 was a Monday) minus the dw of your date, effectively giving the "number of days difference between your date and Monday" or "how many days back do we have to scroll your date to make it into Monday"
( ... -7)%7 - we subtract 7 from it and modulo the result by 7.
We do this because if e.g. DATEFIRST is 7 (Sunday), and your date column is Sunday then your dw is 1, and your known Monday is 2.
This means the result of the dw_for_known_monday - dw_for_your_date is +1 rather than -6
This would then mean that DATEADD will roll your date forwards to the following Monday rather than backwards to the previous Monday
If we subtract 7 off it then the result would definitely be negative, but then we wouldn't want your Mondays (which are 0 days different from the known Monday) to end up doing a DATEADD of -7, so we modulo the result by 7.
This turns any problematic -7 into 0, which means your DATEADD will only ever have a "number of days" argument between -6 and 0
DATEADD(DAY, (DATEPART(dw, '2001-01-01') - DATEPART(dw, YOUR_COLUMN)-7)%7, YOUR_COLUMN) - we then DATEADD the (negative) number of days from the above step
If you want to roll your date backwards to e.g. a Sunday, change the date 2001-01-01 to a date that is a known Sunday (like 2000-12-31), etc

How to check if a datetime variable occurs in the past twelve months

What I am trying to do is to see if a datetime variable has the value of a date at anytime in the past twelve months.
I tried using the DATEDIFF function but then I quickly discovered that this has rounding problems (a comparison between 31st DEC/1st JAN would count as 1 month for example, despite the fact only a day has passed between them)
To make this more accurate I could use -365 days as a parameter rather than -12 months however this still gives the problem of not taking into account leap years (not a common scenario but still one I'd ideally avoid!)
Any ideas as to how I can best go about this?
The problem with leap years can be solved with the DATEADD (datepart , number , date ) function. You can specify minus one year from the current date.
where myDate between DATEADD (year , -1 , GETDATE() ) and GETDATE()
Use DATEADD instead to subtract a year from today and compare that
#datetimevariable >= DATEADD(year, -1, GETDATE())
Note: you don't need to compare the upper bound (GETDATE()) unless you have dates in the future.
Also, do you want exactly one year down to the hour and minute? If not, use this which is safe for datatype precedence if #datetimevariable is datetime or datetime2, and you need this is a WHERE clause or such
#datetimevariable >= CAST(DATEADD(year, -1, GETDATE()) as date)
This works for leap years
SELECT DATEADD(YEAR, -1, '20120301'), DATEADD(YEAR, -1, '20120229')
2011-03-01 00:00:00.000
2011-02-28 00:00:00.000
DATEDIFF works on specific boundary: start of month, start of year, midnight etc which is why it fails in this case
DATEDIFF counts the number of partitions between the two dates, sorry to say there is no rounding issue, it does exactly what it says on the tin. YOUR best solution is probably to used DATEADD
WHERE MyVal BETWEEN GETDATE() AND DATEADD(YEAR, -1, GETDATE())

TSQl: Select Current Date - 6 Days and set time to 12:01 AM

I am trying to get current date - 6 days. That is easy.
Now I am trying to get current date - 6 days + 12:01 AM.
So if today is 3-2-2012 11:14 AM.
I want to get 2-25-2012 12:01 AM
These 2 selects will give me current date - 6, but will not reset the time to 12:01 AM
select getdate()-6
SELECT DATEADD(day, -6, CURRENT_TIMESTAMP);
SELECT DATEADD(minute, 1, DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()) - 6, 0))
is equivalent to
SELECT DATEADD(minute, 1, DATEADD(DAY, DATEDIFF(DAY, '19000101', GETDATE()) - 6, '19000101'))
I think you will find this option faster and more flexible than the varchar implementations. by keeping the data types as they are, you don't have to worry about the vagaries of the cast/convert results.
See Louis Davidson for one of the full explainations:
http://sqlblog.com/blogs/louis_davidson/archive/2011/02/09/some-date-math-fun.aspx
Using the following will give you the result in a datetime format:
SELECT CAST(Convert(varchar(10), DateAdd(d, -6, getdate()), 101)
+ ' 12:01 AM' as datetime)
Result: 2012-02-25 00:01:00.000
Once you have the datetime that you want, you can convert it to many different formats.
Or you can do the following which is in a varchar format:
select Convert(varchar(10), DateAdd(d, -6, getdate()), 110) + ' 12:01 AM'
which results in 02-25-2012 12:01 AM
One less conversion that #Phil Helmer's solution:
SELECT DATEADD(DAY, DATEDIFF(DAY, '19000101', GETDATE()), '1899-12-26T12:01:00')
Since some people are apparently unaware that everything "to the right" of the element specified in that DATEADD/DATEDIFF pair is effectively taken from the right-hand constant. Everything "to the left" (and including the actual element) can be used to achieve offsetting effects.
(The above left/right are assuming that the entire datetime value is being interpreted with year to the left and milliseconds to the right, with all intermediate values in "size" order)
Edited - I've also updated my answer to subsume the -6 into the right-hand value. Its possible to create all kinds of offsetting by picking suitable values for the two constants.
The relationship between the two datetime constants specified in the expression ought to be expressed, at least in a comment alongside the usage. In the above, I'm using 1/1/1900 as a base point, and computing the number of midnight transitions between then and now (as DATEDIFF always works). I'm then adding that number of days onto the point in time 6 days earlier (e.g. 26/12/1899) at exactly 00:01 in the morning...
SELECT DATEADD(dd, -6, DATEDIFF(dd, 0, GETDATE())) + '12:01'