Add time column in SQL SERVER

0

I have a column of type time in a table. With records like:

00:02:15
00:09:47
00:00:25
...

I need, in my select , to get the sum of those minutes in time format . Return example: 00:12:27

I have tried in many ways without success.

    
asked by anonymous 06.03.2018 / 12:12

3 answers

7

You can do this as follows:

create table t1 (id int, t time)

insert into t1 values (1,'00:00:25.0000000')
insert into t1 values (1,'00:12:20.0000000')

insert into t1 values (2,'00:00:02.0000000')
insert into t1 values (2,'00:00:10.0000000')

SELECT ID, CAST(DATEADD(MILLISECOND,SUM(DATEDIFF
(MILLISECOND,0,CAST(T AS DATETIME))),0) AS TIME) FROM t1
GROUP BY ID

See working in SQLFiddle

    
06.03.2018 / 12:25
5

You can use a combination of DATEADD and < a Dref="https://docs.microsoft.com/en-us/sql/t-sql/functions/datediff-transact-sql"> DATEDIFF to calculate the difference in the interval in hours, and CAST at the end to convert to TIME format % like this:

select CAST(DATEADD(ms, SUM(DATEDIFF(ms, '00:00:00.000', hora)), '00:00:00.000') as time) 

Example:

declare @t table (hora time)
insert into @t values ('00:02:15')
insert into @t values ('00:09:47')

select CAST(DATEADD(ms, SUM(DATEDIFF(ms, '00:00:00.000', hora)), '00:00:00.000') as time) from @t

Note that the key is to add the difference between '00: 00: 00' time and bank time.

Based on this OS response in English: link

    
06.03.2018 / 12:42
1

The simplest way to do what you want is:

SELECT 
    ID, CONVERT(TIME,DATEADD (ms, SUM(DATEDIFF(MILLISECOND, 0, T)), 0)) AS TIME 
FROM 
    T1
GROUP BY 
    ID
    
06.03.2018 / 13:47