Average Time on SQL - sql

I am working on a report where I need to find the average amount of time between two timestamps.
To find the time between the time stamps I used:
CAST(( Time2 - Time1 ) as time(0)) AS 'Time Between Stage1 and Stage2'
Now that I have that column, I am trying to get the Average Time Spent Between Stage1 and Stage2. I'm looking for the output to be in the hh:mm:ss format.

Try this:
Format(AVERAGE(CAST(( Time2 - Time1 ) as time(0)), "HH:MM: SS"))

declare #t1 datetime, #t2 datetime
set #t1 = '14:15:54'
set #t2 = '15:12:33'
select #t1,#t2
select cast(dateadd(ms, AVG(datediff( ms, #t1 ,#t2 )), '00:00:00') as time)
First, find the difference using DateDiff in the format of the lowest grain.
Then, find the average
Convert the Average back to date using the DateAdd (you will get errors if you try to use a cast or convert)
Finally, Cast back to a time
replace the variables with your attributes

Related

SQL Server convert varchar hh:mm:ss to time

Is there a way to convert varchar 'hh:mm:ss' format data to time to allowing summing?
DECLARE #InX VARCHAR(10)='09:08:23'
SELECT CAST(#InX AS TIME(0))
You can convert those values to time and for summing you could simply get their difference in seconds from midnight and sum. Result would be in seconds. ie:
DECLARE #times TABLE(t TIME(0));
INSERT INTO #times(t)VALUES('03:20:30'), ('02:10'), ('01:00');
SELECT SUM(DATEDIFF(SECOND, '00:00:00', t))FROM #times AS t;

Is there a quick way to separate date and time from a time stamp in sql?

I am using sql to calculate the average daily temperature and max daily temperature based on a date timestamp in an existing database. Is there a quick way to accomplish this?
I am using dBeaver to do all my data calculations and the following code is what I have used so far:
SELECT
convert(varchar, OBS_TIME_LOCAL , 100) AS datepart,
convert(varchar, OBS_TIME_LOCAL, 108) AS timepart,
CAST (datepart AS date) date_local,
CAST (timepart AS time) time_local
FROM
APP_RSERVERLOAD.ONC_TMS_CUR_ONCOR_WEATHER;
The data format as follows:
ID time_stamp temp
--------------------------------------------
de2145 2018-07-16 16:55 103
There are multiple IDs with 24hrs of temperature data at 1 min increments.
I am not sure if I understand what you need but I will try:
Your question: "Is there a quick way to separate date and time from a time stamp in sql?"
Answer:
select to_char(datec, 'hh24:mi')
, to_char(datec, 'yyyy-mm-dd')
from test;
Use to_char with format to select date part and time part.
You seem to want aggregation:
SELECT convert(date, OBS_TIME_LOCAL) AS datepart,
avg(temp), max(temp)
FROM APP_RSERVERLOAD.ONC_TMS_CUR_ONCOR_WEATHER
GROUP BY convert(date, OBS_TIME_LOCAL);

SQL Server - Check if given date+time is between two datetime variables by exact date+time

I have two datetime columns in a DB table: #Start and #End.
Both columns contain the date and time, for example:
#Start: 2018-10-01 19:00:00
#End: 2018-10-10 23:59:00
I want to know if the current date is exactly between both datetimes considering the dates and the times.
So, 2018-10-08 16:37 and 2018-10-10 23:59:00 would match this range
and 2018-10-11 00:00:00 would not.
(In this case this date is one minute later than the End date, so it is not between my datetime range).
SELECT Id FROM Table1 WHERE GETDATE() BETWEEN Start AND End
I don't use GETDATE() in real code, I use an argument. The problem is that current date argument may contain seconds and milliseconds like 23:59:59.123. My code treats such date as not conforming given range. But I don't care about s/ms.
Is there a workaround?
Update:
The precision I want to achieve is in minutes. So I do not even need to take in account the seconds nor the milliseconds. The date time format I would be working on would be 'yyyy-MM-dd hh-mm' but I do not know how to use the BETWEEN clause converting the Start and End to the shown format so I can compare the dates.
You would seem to want this logic:
WHERE GETDATE() >= Start
AND GETDATE() < DATEADD(minute, 1, End)
Assuming that the time part of End is 23:59:00 it covers all possible values between 23:59:00 and 23:59:59.999...999.
SELECT Id FROM Table1 WHERE GETDATE() BETWEEN '2018-10-01 19:00:00' AND '2018-10-10 23:59:00'
TRY
SELECT Id FROM Table1 WHERE
CONVERT(varchar(16),GETDATE(),121) BETWEEN
CONVERT(varchar(16),[Start], 121)
AND
CONVERT(varchar(16),[END],121);
Example of rounding without strings
DECLARE #GetDateMinutes as datetime2;
DECLARE #X as datetime2 = getdate();
--round to minutes, could be made into a function
SET #GetDateMinutes = dateadd(minute,datepart(minute,#x),dateadd(hour, datepart(hour,#x),cast(CAST(#x as date) as datetime2)))
select #x, #GetDateMinutes
Truncate the seconds using the technique described here to avoid all string conversions, then just do your comparison. Here's a fully contained example that uses cross apply and values to encapsulate the truncation logic for start and end:
-- truncate minutes from current date time
declare #currentDateTime datetime2(0) = DateAdd(minute, DateDiff(minute, 0, Convert(datetime2(0), N'2018-10-01 23:58:32.912')), 0);
select #currentDateTime as CurrentDateTime
, a.*
from (values -- create a table of dummy values
(Convert(datetime2(3), N'2018-10-01 19:48:14.735'), Convert(datetime2(3), N'2018-10-10 02:00:00.000'))
, (Convert(datetime2(3), N'2018-10-01 22:43:19.532'), Convert(datetime2(3), N'2018-11-01 12:17:26.663'))
) as a (StartDateTime, EndDateTime)
cross apply (values(
-- truncate minutes from start date time
DateAdd(minute, DateDiff(minute, 0, Convert(datetime2(0), a.StartDateTime)), 0)
-- truncate minutes from end date time
, DateAdd(minute, DateDiff(minute, 0, Convert(datetime2(0), a.EndDateTime)), 0)
)) as b (StartDateTimeWithoutSeconds, EndDateTimeWithoutSeconds)
where #currentDateTime between b.StartDateTimeWithoutSeconds and b.EndDateTimeWithoutSeconds;
Your data appears to already have the s/ms truncated from start and end but figured I'd apply the same logic to all values involved just to be consistent. Here's the formula for stripping s/ms without all the "noise" from the example:
DateAdd(minute, DateDiff(minute, 0, Convert(datetime2(0), <SomeDateTime>)), 0)

How to Sum (Time(n)) in Sql Server?

How want to use the sum of the time(n) operator so that i can calculate the overall total of the time but Sql server saying can't add the Time(n) column
i have a casted column which contain difference of two dates, and being casted as Time(n) by me. Now i want to add those column to get how much time i had used in total How much hours minute and seconds so i apply
select Sum(cast ((date1-date2) as Time(0))) from ABC_tbl
where date1 is reaching time and date2 is startingtime in Date format and i want to total of all hours
Convert the time to an integer value before you sum it (for example, seconds):
SELECT SUM(
datediff(second, '00:00:00', [TimeCol])
)
FROM
...
Replace [TimeCol] with the name of the Time(n) column. This gives you the total time in seconds, which you can then easily convert to minutes, hours, etc...
Hope this example help you.
DECLARE #A TABLE (SD TIME(0),ED TIME(0))
INSERT INTO #A VALUES
('09:01:09','17:59:09'),
('09:08:09','16:10:09'),
('08:55:05','18:00:00')
SELECT SUM(DATEDIFF(MINUTE,SD,ED)) SUM_IN_MINUTES,
SUM(DATEDIFF(HOUR,SD,ED)) SUM_IN_HOURS
FROM #A
Result:
SUM_IN_MINUTES | SUM_IN_HOURS
---------------------------------------
1505 | 25
select Sum(DATEDIFF(Minute,date1,date2)) AS TIME from ABC_tbl
u have to calculate the date difference with DATEDIFF function then use SUM function to calculate your sum of time.
you can change Minute to Second-Hour-month etc..
Try this:
DECLARE
#MidnightTime TIME = '00:00:00.0000000',
#MidnightDateTime DATETIME2 = '0001-01-01 00:00:00.0000000';
SELECT SumOfTime = DATEADD(SECOND, SUM ( DATEDIFF(SECOND, #MidnightTime, x.Col1) ), #MidnightDateTime)
FROM (VALUES
(1, CONVERT(TIME, '10:10:10.0000001')),
(2, CONVERT(TIME, '00:00:05.0000002')),
(3, CONVERT(TIME, '23:59:59.0000003'))
) x(ID, Col1)
/*
SumOfTime
---------------------------
0001-01-02 10:10:14.0000000 = 1 day (!), 10 hours, 10 minutes, 14 seconds
*/
Note: instead of SECOND you could use another precision: MINUTE, HOUR or ... NANOSECOND (see section Arguments > datepart). Using a higher precision could leads to Arithmetic overflow errors (use CONVERT(BIGINT|NUMERIC(...,0), ...).
Note #2: because the precision is SECOND the result (SumOfTime) has 0000000 nanoseconds.

Calculate the time after converting into a new datatype

Goal:
To display data with this list:
Hour
-----
2
2,5
1
Problem:
Is it any possibiltiy to convert column StartTime and EndTime into specific datatype and then doing a calculacution of X1- X2
CREATE TABLE Data
(
StartTime VARCHAR(5),
EndTime VARCHAR(5),
)
GO
INSERT INTO Data(StartTime,EndTime)
SELECT '10:00','12:00' UNION ALL
SELECT '13:30','16:00' UNION ALL
SELECT '14:00','15:00' UNION ALL
GO
EDITED: To get mins in decimals
SELECT ROUND(CAST( Mins AS FLOAT)/60,2) AS [hour]
FROM (
SELECT DATEDIFF(minute, CAST(StartTime AS TIME),CAST(EndTime AS TIME)) AS Mins
FROM Data
) A
SELECT DATEDIFF(mi, CONVERT(DATETIME, StartTime), CONVERT(DATETIME, EndTime))
/ 60.0 AS Hour
FROM Data
It work's for your example data, but you should check if EndTime could be the next day, like:
StarTime: 22:30
EndTime: 01:20
Is that escenario possible? If it is, you must store the date for both Start and End times, not only the hour.
If you are using SQL-SERVER 2008, then why not just use the time object. You could then run the appropriate time comparison functions. If not, you can still make it work by converting to a datetime and running comparison functions. I believe a convert with just a time to a datetime will result in the date as the minimum date.