Show average difference between two time fields as MM:SS in SQL - sql

I am using SQL Server 2008. I have several rows of start_time and end_time. I want to calculate the average difference between these two times in a MM:SS format.
start_time | end_time
10:15:30 | 10:15:45
10:45:00 | 10:47:30
Row 1 would be a difference of 00:15, and row 2 would be a difference of 02:30. The average of the entire dataset would be 01:23 (1 minute and 23 seconds).
The code I'm using looks like the following, but only returns an integer.
AVG(DATEDIFF(MI,start_time,end_time))
Thanks in advance for your help.

You're close, but you should use DateDiff() to get the average number of seconds between the two fields, rather than the average number of minutes.
With SQL Server 2008 R2, you don't have access to TIMEFROMPARTS() which would simplify the display greatly, so you'll have to convert this into a VARCHAR to get the format you want.
;With AverageSeconds As
(
Select Avg(DateDiff(Second, Start_Time, End_Time))) AvgSec
From YourTable
)
Select Right('00' + Convert(Varchar, (AvgSec / 60)), 2)
+ ':'
+ Right('00' + Convert(Varchar, (AvgSec % 60)), 2)
From AverageSeconds

You can convert the dates in unixtimestamp and then convert the seconds in a string.

Alternatively
right(convert(varchar(20), Dateadd(second, Avg(Datediff(second, Start_Time, End_Time)), 0), 120), 5)

Related

how to get sum of time as float

A table has a time column in float datatype is given as:
40m
11m
2m
0m
3m
1m
1m
How can I sum these values to get it in hours and minutes?
You could use Gordon's answer, which directly leverages SQL Server's built in time ability. An alternative would be the "brute force" approach of computing the number of hours and minutes represented by the sum of your time column:
WITH cte AS (
-- strip off 'm' units and convert to numbers
SELECT CONVERT(int, REPLACE(time, 'm', '')) AS time
FROM yourTable
)
SELECT
CONVERT(varchar(10), FLOOR(SUM(time) / 60)) + ':' +
CONVERT(varchar(10), FLOOR(SUM(time) % 60)) AS timestamp
FROM cte;
Demo
The demo shows that the logic holds up even if the number of minutes in your column should exceed 24 hours.
You can use dateadd() and then cast the result back to a time:
select cast(dateadd(minute, sum(col), 0) as time)
from t;
Note: This only works up to 23:59:00. The SQL Server time type does not support larger values.
Here is a rextester.

How to print hour values in an hourly report in SQL

I'm building hourly report from SQL Table CONFIRMATION via SQL Query. Query absolutely runs fine and gives proper results as follow:
SELECT DATEPART(hh, CONFIRMATION.DATECOMPLETE) AS hour, sum( CONFIRMATION.QUANTITY) Units
FROM CONFIRMATION
WHERE CONFIRMATION.DATECOMPLETE >= '11/18/2015'
GROUP BY DATEPART(hh, CONFIRMATION.DATECOMPLETE)
I want to change Hour to have follwoing instead of hour number:
Hour Units
10:00 - 11:00 4
11:00-12:00 8
How can I achieve that?
Thanks
You can convert the datetime hour component into a string to format the 10:00-11:00. You can then calculate the end time by adding 1 to the hour component and modulo 24 to wrap around at midnight.
CONVERT(varchar(2),DATEPART(hh,CONFIRMATION.DATECOMPLETE)) + ':00-' + CONVERT(varchar(2), (DATEPART(hh,CONFIRMATION.DATECOMPLETE)+1) % 24) + ':00'
When putting parts of dates together using concatenation, datename() is much better than datepart():
SELECT (DATENAME(hour, c.DATECOMPLETE) + ':00-' +
DATENAME(hour, DATEADD(hour, 1, c.DATECOMPLETE)) + ':00'
) as period,
SUM(c.QUANTITY) as Units
FROM CONFIRMATION c
WHERE c.DATECOMPLETE >= '2015-11-18'
GROUP BY (DATENAME(hour, c.DATECOMPLETE) + ':00-' +
DATENAME(hour, DATEADD(hour, 1, c.DATECOMPLETE)) + ':00'
);
In addition:
Use ISO standard date formats. Either YYYY-MM-DD or YYYYMMDD.
Table aliases make the query easier to write and to read.

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.

how to add 2 varchar columns in sql

I have timediff field as varchar
I want to find sum of this field but it gives error as
"Syntax error converting the varchar value '02:00' to a column of data type int."
My timediff is like
02:00
03:00
04:00
i want to add and should display 9 in sql
please help me
thanks for helping me
You can't use SUM on a varchar column. Take a look at the documentation here.
You haven't given us much information about what you are storing or how you want it summed, but your best bet might be to parse out the number before your colon, convert it to an int and sum that.
Good luck!
If you are talking about MS SQL
You could do something like this
first convert your hour representation to minutes by this
select (CONVERT(int,SUBSTRING('02:00',1,2))*60) +
CONVERT(int,SUBSTRING('02:00',4,2))
Then use that minutes representation to perform addition like this
select
DATEADD(
minute,
(select (CONVERT(int,SUBSTRING('02:00',1,2))*60) +
CONVERT(int,SUBSTRING('02:00',4,2))),
getdate())
If your final goal is to get sum of all datadiff records in hh:mm then first store datediff in minutes instead of hh:mm which you asked here.
How to store DateDiff in minutes:
SELECT DATEDIFF(second,CAST(<timepart> AS DATETIME)
, CAST(<timepart> AS DATETIME))/60.0 AS MIN_DIFF;
For example
SELECT DATEDIFF(second,CAST('10:00 AM' AS DATETIME)
, CAST('11:15 AM' AS DATETIME))/60.0 AS MIN_DIFF;
How to do sum of all minutes in hh:mm
SELECT CAST((<total minutes> / 60) AS VARCHAR(8)) + ':'
+ CAST((<total minutes> % 60) AS VARCHAR(2))
For example
SELECT CAST((390 / 60) AS VARCHAR(8)) + ':'
+ CAST((390 % 60) AS VARCHAR(2))
See this fiddle for all your answers.

Calculate the SUM of the Column which has Time DataType:

I want to calculate the Sum of the Field which has Time DataType.
My Table is Below:
TableA:
TotalTime
-------------
12:18:00
12:18:00
Here I want to sum the two time fields.
I tried the below Query
SELECT CAST(
DATEADD(MS, SUM(DATEDIFF(MS, '00:00:00.000',
CONVERT(TIME, TotalTime))), '00:00:00.000'
) AS TOTALTIME)
FROM [TableA]
But it gives the Output as
TOTALTIME
-----------------
00:36:00.0000000
But My Desired Output would be like below:
TOTALTIME
-----------------
24:36:00
How to get this Output?
You could sum the total number of seconds, or datediff(second,0,datecolumn). You can format that as a time string with some math. For example, the total number of minutes is totalseconds / 60 % 60. For example:
select cast(sum(datediff(second,0,dt))/3600 as varchar(12)) + ':' +
right('0' + cast(sum(datediff(second,0,dt))/60%60 as varchar(2)),2) +
':' + right('0' + cast(sum(datediff(second,0,dt))%60 as varchar(2)),2)
from TestTable
Working code at SQL Fiddle.
24:36 is the same as 00:36(Next day)
Your query is working fine the results are correct,
24:36 is the time 00:36 for next day.
You can display maximum 24 hrs. You are not using any day thats why every 24 hrs =0 hrs for next day.
Just change the column values and you can see that.
It would be a tad longwinded, but if you wanted to avoid the day rollover but you could split the second TIME into constituent datepart()'s and then add those on? (even display as a varchar if it's necessary to have an hour value greater than 24.
TRY THIS.
SELECT
CONVERT(VARCHAR(MAX),SUM(DATEPART(HH,CAST(YOUR_FIELD AS DATETIME)))+
(SUM(DATEPART(MINUTE,CAST(YOUR_FIELD AS DATETIME)))/60) +
(SUM(DATEPART(MINUTE,CAST(YOUR_FIELD AS DATETIME)))%60 +
(SUM(DATEPART(SECOND,CAST(YOUR_FIELD AS DATETIME)))/60))/60) + ':' +
RIGHT('00' + CONVERT(VARCHAR(MAX),
(SUM(DATEPART(MINUTE,CAST(YOUR_FIELD AS DATETIME)))%60+
(SUM(DATEPART(SECOND,CAST(YOUR_FIELD AS DATETIME)))/60))%60),2) + ':' +
RIGHT('00' + CONVERT(VARCHAR(MAX),SUM(DATEPART(SECOND,
CAST(YOUR_FIELD AS DATETIME)))%60),2) AS YOUR_FIELD
FROM YOUR_TABLE