Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of DateTime difference in sql (HH.MM)

I have SQL Table like Where DateDiff is in format (hh.mm)

DateDiff   ATM
1.45       121
1.50       121
1.50       121

When i do Sum of DateDiff by Group by on ATM it will show result like

4.45    121

But the actual Date Time Difference should be

5.25     121

How can we achieve the same in SQL Query

Select Sum(Cast(Convert(Varchar(10),DATEDIFF(HOUR,TicketRaisedOn,ClosedOn))+'.'+
Convert(Varchar(10),DATEDIFF(MINUTE,TicketRaisedOn,ClosedOn)%60) as Numeric(18,2)))[Down Time],ATM 
From Ticket Where Closed=1 And DATEPART(DAYOFYEAR,GETDATE())=DATEPART(DAYOFYEAR,TicketRaisedOn) 
Group BY ATM Order By [Down Time] Desc

TicketRaisedOn & ClosedOn are of DateTime

Database is SQL Server 2008

Above query will print result like this (But its wrong as it will sum it as number not as date time format)

Down Time       ATM
16.95           282
14.46           1811
14.20           52
14.04           936

Sample Data

Select TicketRaisedOn,ClosedOn,ATM 
From Ticket 
Where ATM=282 And DATEPART(DAYOFYEAR,GETDATE())=DATEPART(DAYOFYEAR,TicketRaisedOn) 
And Closed=1

TicketRaisedOn          ClosedOn                ATM
2012-12-21 01:15:23.793 2012-12-21 15:11:59.240 282
2012-12-21 16:42:29.820 2012-12-21 18:21:30.797 282
like image 235
Shaggy Avatar asked Dec 21 '12 13:12

Shaggy


2 Answers

Do the summing before the formatting

SELECT
  ATM,
  CONVERT(VARCHAR(10), SUM(DATEDIFF(Minute, TicketRaisedOn, ClosedOn)) / 60)
  + '.' +
  RIGHT('00' + CONVERT(VARCHAR(2), SUM(DATEDIFF(Minute, TicketRaisedOn, ClosedOn)) % 60), 2)
FROM Ticket
GROUP BY ATM

Sql Fiddle: http://sqlfiddle.com/#!3/eca01/1

like image 180
msmucker0527 Avatar answered Oct 15 '22 11:10

msmucker0527


What you are doing doesn't work, because 1.5 represents one and a half hours, not one hour and 50 minutes.

To get what you want, do the arithmetic in a small unit, such as seconds, then convert this to a datetime, and then the datetime to a final representation. Here is an example:

select right(convert(varchar(255),
                     DATEADD(second, DATEDIFF(s, TicketRaisedOn,ClosedOn), cast(0 as datetime)),
                     120),
             8)
like image 39
Gordon Linoff Avatar answered Oct 15 '22 09:10

Gordon Linoff