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.
Share
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.
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.
Note the misleading “03:00:00” for the 27-hour difference on id number 3.
Function to format elapsed time in SQL Server