How to convert number of minutes to hh:mm format in TSQL?

前端 未结 12 2003
情话喂你
情话喂你 2020-12-03 09:48

I have a select query that has DURATION column to calculate number of Minutes . I want to convert those minutes to hh:mm format.

12条回答
  •  一个人的身影
    2020-12-03 10:17

    This function is to convert duration in minutes to readable hours and minutes format. i.e 2h30m. It eliminates the hours if the duration is less than one hour, and shows only the hours if the duration in hours with no extra minutes.

    CREATE FUNCTION [dbo].[MinutesToDuration]
    (
        @minutes int 
    )
    RETURNS nvarchar(30)
    
    AS
    BEGIN
    declare @hours  nvarchar(20)
    
    SET @hours = 
        CASE WHEN @minutes >= 60 THEN
            (SELECT CAST((@minutes / 60) AS VARCHAR(2)) + 'h' +  
                    CASE WHEN (@minutes % 60) > 0 THEN
                        CAST((@minutes % 60) AS VARCHAR(2)) + 'm'
                    ELSE
                        ''
                    END)
        ELSE 
            CAST((@minutes % 60) AS VARCHAR(2)) + 'm'
        END
    
    return @hours
    END
    

    To use this function :

    SELECT dbo.MinutesToDuration(23)
    

    Results: 23m

    SELECT dbo.MinutesToDuration(120)
    

    Results: 2h

    SELECT dbo.MinutesToDuration(147)
    

    Results: 2h27m

    Hope this helps!

提交回复
热议问题