Click here to Skip to main content
15,891,677 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
 How i sum or aggregate time data in sql server  

hh:mm:ss
00:01:03
00:00:30
00:00:31
00:00:34
00:00:33
00:00:31
00:00:57
00:00:36
--------------
0:01:39


What I have tried:

sql server return error:
"Msg 8117, Level 16, State 1, Line 4
Operand data type time is invalid for sum operator."
Posted
Updated 24-Aug-21 23:44pm
v3

Sorry, but your calculations are wrong:
hh:mm:ss
00:01:03
00:00:30
00:00:31
00:00:34
00:00:33
00:00:31
00:00:57
00:00:36
--------------
00:01:39
00:05:15


I'd suggest to use DATEPART[^] and DATEADD[^] functions, as follow:

SQL
CREATE TABLE toj
(
  jobtime time
);

INSERT INTO toj (jobtime)
VALUES('00:01:03'),
('00:00:30'),
('00:00:31'),
('00:00:34'),
('00:00:33'),
('00:00:31'),
('00:00:57'),
('00:00:36');

SELECT DATEADD(hh, t.TotalHours, DATEADD(n, t.TotalMinutes, DATEADD(ss, t.TotalSeconds, CAST('00:00:00' AS time)))) AS TotalTime
FROM (
  SELECT SUM(DATEPART(hh, jobtime)) AS TotalHours, 
    SUM(DATEPART(n, jobtime)) AS TotalMinutes, 
    SUM(DATEPART(ss, jobtime)) AS TotalSeconds
  FROM toj
) AS t;


Result:
TotalTime
00:05:15.0000000


See: SqlFiddle[^]
 
Share this answer
 
Comments
Richard Deeming 25-Aug-21 7:24am    
NB: At least in SQL Server, the time type[^] can only hold values from 00:00:00 to 23:59:59.999..., so this code could very easily overflow.
Maciej Los 25-Aug-21 7:46am    
Agree. OP doesn't mention that. I cannot solve further problems ;)
midree 27-Aug-21 6:33am    
thanks for Help
Maciej Los 27-Aug-21 8:48am    
You're very welcome.
You can't add time any more than you can add telephone numbers: convert it to seconds by extracting the hours and multiplying by 60, then add in the minutes and multiply that by 60, then add in the seconds.

You can then sum those to get a total in seconds.
Then convert that back to hour, minute, and second counts using the divide and modulus operators.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900