sql-server-2008datetimeelapsedtime

SQL Server - calculate elapsed time between two datetime stamps in HH:MM:SS format


I have a SQL Server table that has a "Time" column. The table is a log table the houses status messages and timestamps for each message. The log table is inserted into via a batch file. There is an ID column that groups rows together. Each time the batch file runs it initializes the ID and writes records. What I need to do is get the elapsed time from the first record in an ID set to the last record of the same ID set. I started toying with select Max(Time) - Min(Time) from logTable where id = but couldn't figure out how to format it correctly. I need it in HH:MM:SS.


Solution

  • SQL Server doesn't support the SQL standard interval data type. Your best bet is to calculate the difference in seconds, and use a function to format the result. The native function CONVERT() might appear to work fine as long as your interval is less than 24 hours. But CONVERT() isn't a good solution for this.

    create table test (
      id integer not null,
      ts datetime not null
      );
    
    insert into test values (1, '2012-01-01 08:00');
    insert into test values (1, '2012-01-01 09:00');
    insert into test values (1, '2012-01-01 08:30');
    insert into test values (2, '2012-01-01 08:30');
    insert into test values (2, '2012-01-01 10:30');
    insert into test values (2, '2012-01-01 09:00');
    insert into test values (3, '2012-01-01 09:00');
    insert into test values (3, '2012-01-02 12:00');
    

    Values were chosen in such a way that for

    This SELECT statement includes one column that calculates seconds, and one that uses CONVERT() with subtraction.

    select t.id,
           min(ts) start_time,
           max(ts) end_time,
           datediff(second, min(ts),max(ts)) elapsed_sec,
           convert(varchar, max(ts) - min(ts), 108) do_not_use
    from test t
    group by t.id;
    
    ID  START_TIME                 END_TIME                   ELAPSED_SEC  DO_NOT_USE
    1   January, 01 2012 08:00:00  January, 01 2012 09:00:00  3600         01:00:00
    2   January, 01 2012 08:30:00  January, 01 2012 10:30:00  7200         02:00:00
    3   January, 01 2012 09:00:00  January, 02 2012 12:00:00  97200        03:00:00
    

    Note the misleading "03:00:00" for the 27-hour difference on id number 3.

    Function to format elapsed time in SQL Server