Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transact-SQL to sum up elapsed time

I have a table in my database the records start and stop times for a specific task. Here is a sample of the data:

Start                       Stop
9/15/2008 5:59:46 PM        9/15/2008 6:26:28 PM
9/15/2008 6:30:45 PM        9/15/2008 6:40:49 PM
9/16/2008 8:30:45 PM        9/15/2008 9:20:29 PM
9/16/2008 12:30:45 PM       12/31/9999 12:00:00 AM

I would like to write a script that totals up the elapsed minutes for these time frames, and wherever there is a 12/31/9999 date, I want it to use the current date and time, as this is still in progress.

How would I do this using Transact-SQL?

like image 341
mattruma Avatar asked Sep 17 '08 10:09

mattruma


People also ask

How do you calculate elapsed time in SQL?

SQL> create or replace function elapsed( 2 ts1 in timestamp, 3 ts2 in timestamp 4 ) return varchar2 sql_macro(scalar) is 5 begin 6 return ' 7 extract(day from (ts2-ts1))*86400+ 8 extract(hour from (ts2-ts1))*3600+ 9 extract(minute from (ts2-ts1))*60+ 10 extract(second from (ts2-ts1))'; 11 end; 12 / Function created.

What is total elapsed time in SQL Server?

The cpu time is the total time spent by the cpu resources on a server. If a server has five cpus, and each cpu runs 3 milliseconds concurrently with the other cpus, then the total cpu time is 15 milliseconds. The elapsed time is the total time taken by SQL Server.


2 Answers

SELECT  SUM( CASE  WHEN Stop = '31 dec 9999' 
                   THEN DateDiff(mi, Start, Stop)
                   ELSE DateDiff(mi, Start, GetDate())
             END ) AS TotalMinutes 
FROM    task

However, a better solution would be to make the Stop field nullable, and make it null when the task is still running. That way, you could do this:

SELECT  SUM( DateDiff( mi, Start, IsNull(Stop, GetDate() ) ) AS TotalMinutes 
FROM    task
like image 180
AJ. Avatar answered Oct 03 '22 00:10

AJ.


I think this is cleaner:

   SELECT  SUM(
               DATEDIFF(mi, Start, ISNULL(NULLIF(Stop,'99991231'), GetDate()))
              ) AS ElapsedTime
   FROM Table
like image 44
GilM Avatar answered Oct 02 '22 23:10

GilM