SQL Server SUM

Guys, My litle problem looks like this: I have these columns: PHONE_NR, TIME (time field), caller number value and call duration. I need to group a phone number and sum up minutes. Filds looks like this:

 nr          time 
726028xxx 00:07:07 
735560css 00:07:37 
726028xxx 00:07:55 

      

+2


source to share


3 answers


SELECT PHONE_NR, SUM(DATEPART(minute, TIME)) FROM [table] GROUP BY PHONE_NR;

      

As far as I know, this should work for both SQL Server DATETIME

and TIME

2008 datatypes .

Example:

DECLARE @tbl TABLE
(
    phone_nr varchar(10),
    call_time TIME
);

INSERT INTO @tbl VALUES ('726028xxx', '00:07:07');
INSERT INTO @tbl VALUES ('735560css', '00:07:37');
INSERT INTO @tbl VALUES ('726028xxx', '00:07:55');

SELECT phone_nr, SUM(DATEPART(minute, call_time)) AS total_call_time FROM @tbl GROUP BY phone_nr;

      

Results in:

phone_nr  | minutes
726028xxx | 14
735560css | 7

      



EDIT

This version is identical to the one above, except that it also takes into account seconds and hours (e.g. 1 hour 7 min 07 sec = 67.117 minutes), so it is much more accurate.

SELECT 
    phone_nr, 
    SUM(CAST(DATEPART(second, call_time) + (DATEPART(minute, call_time) * 60) + (DATEPART(hour, call_time) * 3600) AS decimal) / 60) AS total_call_time
FROM 
    @tbl
GROUP BY
    phone_nr;

      

The results are as follows if the first entry was 01:07:07

.

phone_nr  | minutes
726028xxx | 75.033332
735560css | 7.616666

      

+5


source


You can use DATEDIFF to get the total number of minutes that have passed since "zero"



SELECT
 [PHONE_NR],
 SUM(DATEDIFF(minute, '00:00:00', [TIME]))
FROM
 [YourTable]
GROUP BY
 [PHONE_NR]

      

+1


source


declare @v1 varchar(50)
declare @v2 varchar(50)
set @v1='03:10'
set @v2='01:50'

--select cast(left(v1,2) as int) + cast(left(v2,2)as int)

select 
cast(
cast(left(@v1,2) as int) + cast(left(@v2,2)as int)
+(cast(right(@v1,2) as int) + cast(right(@v2,2) as int))/60 as varchar)

+':'+cast(( cast(right(@v1,2) as int) + cast(right(@v2,2) as int))%60 as varchar)

      

0


source







All Articles