Is there a way to add fractions in dateadd - sql

I was surprised to see this query gives two columns with identical values
select
dateadd(hour, -1.5, GETUTCDATE()) as OneAndAHalf,
dateadd(hour, -1, GETUTCDATE()) as One
Is it possible to use dateadd in this way, or am I going to have to calculate the datetime in code?

According to the Docs the answer is no. You cannot add a non-integer value (either as a literal or as an expression) as 'number' in the DATEADD function.
As other members mentioned: switch the DATEPART to an appropriate interval (like minutes) and use that instead. To add "fractions of a second" you could use 'millisecond' which adds thousandth's of a second.
select getdate()
union all
select dateadd(millisecond,100, getdate())
(No column name)
2021-08-06 11:15:04.260
2021-08-06 11:15:04.360
Syntax SQL
DATEADD (datepart , number , date )
number An expression that can resolve to an int that DATEADD adds to a
datepart of date. DATEADD accepts user-defined variable values for
number. DATEADD will truncate a specified number value that has a
decimal fraction. It will not round the number value in this
situation.

Multiply your increment by 60 and add it as minutes (or multiply them by 3600 and add it as seconds)
select
dateadd(minute, -1.5 * 60, GETUTCDATE()) as OneAndAHalf,
dateadd(minute, -1 * 60, GETUTCDATE()) as One
select
dateadd(second, -1.5 * 3600, GETUTCDATE()) as OneAndAHalf,
dateadd(second, -1 * 3600, GETUTCDATE()) as One

Related

Counting Calls by Half-Hour intervals

I was trying to get the count of calls per half-hour interval.
Couldn't figure it out.
select
count(call_id) as '#Calls',
1/2 h(date_time) as 'Call_Interval'
from My_Table
One method to aggregate by various time intervals is with DATEADD and DATEDIFF:
SELECT
COUNT(*) as '#Calls',
DATEADD(minute, (DATEDIFF(minute, '', date_time) / 30) * 30, '') as Call_Interval
FROM dbo.My_Table
GROUP BY DATEADD(minute, (DATEDIFF(minute, '', date_time) / 30) * 30, '')
ORDER BY Call_Interval;
On a side note, the empty string constant above represents the default value for datetime. The default values for datetime and other temporal types are listed below, expressed in ISO 8601 string format:
Data Type
Default Value
date
1900-01-01
datetime
1900-01-01T00:00:00
datetime2
1900-01-01T00:00:00
datetimeoffset
1900-01-01T00:00:00+00:00
smalldatetime
1900-01-01T00:00:00
time
00:00:00
Time interval calculations with a datepart more granular than minute (i.e. second, millisecond, and microsecond) may require a more recent base datetime value than the default value (e.g. 2020-01-01T00:00:00) to avoid overflow.

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

SQL Datetime as time query

I would like the below select statement to be show as time rather than datetime. I'm aware that a cast as solution is likely however given I am trying to Cast as a "grouped by time", I am not finding a solution.
SELECT
DATEADD(hour, DATEDIFF(hour, 0,dbo.tbReceiptLine.Time), 0) AS Hourly,
DATEADD(minute, DATEDIFF(minute, 0, dbo.tbReceiptLine.Time) / 30 * 30, 0) AS [30 Mins]
I would like to show this as time only.
In SQL Server 2008 onwards you can cast to time datatype:
SELECT CAST(dbo.tbReceiptLine.Time as time)
See The ultimate guide to the datetime datatypes

SQL add Datetime add hour add Minute

In my table I have DateTime, Hour column.
example : 2012-05-14 00:00:00.000 and 1230
How can I add this hour column into my Datetime column, so I can have
2012-05-14 12:30:00.000
I tried with this:
SELECT DATE_DEBUT, HEURE_DEBUT,
DATEADD(hour, CONVERT(int, SUBSTRING(HEURE_DEBUT, 0, 2)), DATE_DEBUT) AS DateTemp,
DATEADD(hour, CONVERT(int, SUBSTRING(HEURE_DEBUT, 2, 2)), DateTemp) AS DateComplete
FROM ESPTEMPS_PROGRAMMATION
but it does not work.
thanks you in advance,
Stev
From what I understand, you want to add the first two digits as hour, the second two as minute - but you're not doing this in your DATEADD calls - you're adding both parts as HOUR - try this instead:
SELECT DATE_DEBUT, HEURE_DEBUT,
DATEADD(MINUTE, CONVERT(int, SUBSTRING(HEURE_DEBUT, 3, 2)),
DATEADD(HOUR, CONVERT(int, SUBSTRING(HEURE_DEBUT, 1, 2)), DATE_DEBUT))
FROM ESPTEMPS_PROGRAMMATION
Here I'm using two nested DATEADD - the inner DATEADD adds the hours, the outer adds the minutes onto the result of adding the hours.
Also: SUBSTRING in SQL Server is 1-based, e.g. the first character of a string is at position 1 (not 0, as you seem to assume)

DateDiff in SQL Server asking for help

I am using SQL Server 2008. I have a table which has a datetime type column called CreateTime. I need to select all the records from this table whose CreateTime is more than 3 days and half an hour from current time (UTC time). I am using T-SQL store procedure.
BTW: The CreateTime column is some time in the past time.
I have taken quite some time to learn and search for help from MSDN for DateDiff, but cannot figure out. Could anyone show me a sample please?
thanks in advance,
George
You can select and add a WHERE clause with a DATEDIFF using minutes:
SELECT (fields)
FROM (table)
WHERE
DATEDIFF(MINUTE, CREATETIME, getutcdate()) <= (3*24*60 + 30)
And of course, if you only wants those rows which are MORE than 3 days and 30 minutes away, just use the opposite:
WHERE
DATEDIFF(MINUTE, CREATETIME, getutcdate()) > (3*24*60 + 30)
A sample:
SELECT
DATEDIFF(MINUTE, '2009-08-01 08:00:00', getutcdate()),
DATEDIFF(MINUTE, '2009-07-31 20:00:00', getutcdate()),
DATEDIFF(MINUTE, '2009-07-23 20:00:00', getutcdate())
gives as result:
96 816 12337
So the first two dates are still within your 4350 minute bracket (less than 3 days and 30 minutes ago), while the third date is further away.
Marc
You need DATEADD:
WHERE DATEADD(minute, 4350, CreateTime) <= getutcdate()
Or, as you mentioned, you can use DATEDIFF:
WHERE DATEDIFF(minute, CreateTime, getutcdate()) <= 4350
(4350 is '3 days and 30 minutes' in minutes)
One minor quibble with the given answers, though they are correct. Don't apply the function to the column: apply the function to the comparison value.
If CREATETIME is indexed then it's a scan rather than seek with the function on the column.
You don't need millions of rows for this to be a problem.
Adapting the answer of marc_s:
SELECT (fields)
FROM (table)
WHERE
CREATETIME <= DATEADD(MINUTE, - (3*24*60 + 30), getutcdate())