SQL server, Converting Seconds to Minutes, Hours, Days

后端 未结 5 1284
别那么骄傲
别那么骄傲 2020-12-06 13:20

I have a database column containing an integer value that represents a systems up time in seconds. I\'d really like a query to be able to show me that up time in a easy to r

5条回答
  •  不思量自难忘°
    2020-12-06 14:01

    You can convert seconds to days by dividing by 86400

    You can convert seconds to hours by dividing by 3600, but you need to get the remainder (by subtracting off the total days converted to hours)

    You can convert seconds to minutes by dividing by 60, but you need to get the remainder (by subtracting off the total hours converted to minutes)

    Seconds you can just report, but like minutes you want to only report the remainder of seconds (by sutracting off the total minutes converted to seconds)

    SELECT      FLOOR( UpTime / 86400 ) AS DAYS
            ,   FLOOR( ( UpTime / 3600 ) - FLOOR( UpTime / 86400 ) * 24 ) AS HOURS
            ,   FLOOR( ( UpTime / 60 ) - FLOOR( UpTime / 3600 ) * 60 ) AS MINUTES
            ,   UpTime - FLOOR( UpTime / 60 ) * 60 AS SECONDS
    FROM        ( SELECT 269272 AS UpTime ) AS X
    

    269272 represents 3 days (259200 seconds), 2 hours (7200 seconds), 47 minutes (2820 seconds) and 52 seconds.

    This query produces:

    | DAYS | HOURS | MINUTES | SECONDS |
    ------------------------------------
    |    3 |     2 |      47 |      52 |
    

    Substituting 125 (2 minutes, 5 seconds) for 259200 will produce:

    | DAYS | HOURS | MINUTES | SECONDS |
    ------------------------------------
    |    0 |     0 |       2 |       5 |
    

    To convert this to a string representation, you can use SQL Server 2012's FORMAT function:

    SELECT  CASE
                WHEN DAYS > 0 THEN
                    FORMAT( DAYS, '##' ) + ' Day(s) ' + FORMAT( HOURS, '##' ) + ' Hour(s)'
                ELSE
                    FORMAT( HOURS, '##' ) + ':' + FORMAT( MINUTES, '##' ) + ' Hour(s) Minute(s)'
            END AS UpTimeString
    FROM (
        SELECT      FLOOR( UpTime / 86400 ) AS DAYS
                ,   FLOOR( ( UpTime / 3600 ) - FLOOR( UpTime / 86400 ) * 24 ) AS HOURS
                ,   FLOOR( ( UpTime / 60 ) - FLOOR( UpTime / 3600 ) * 60 ) AS MINUTES
                ,   UpTime - FLOOR( UpTime / 60 ) * 60 AS SECONDS
        FROM        ( SELECT 125 AS UpTime ) AS X
    ) AS UptimeSubselect
    

提交回复
热议问题