How to split minutes into days, hours and minutes in tsql

蓝咒 提交于 2019-12-22 11:09:19

问题


I have a column which consist of minutes. Is there any simple way to split minutes column into one column which shows days, hours, minutes only?

DURATION              
-----------
67           ==> 1 hour, 7 minutes
1507         ==> 1 day, 1 hour, 7 minutes
23           ==> 23 minutes

I googled for solution but I didn't find any solution similar for me. I want to show this in a report but trying to find how can I solve this column looks meaningfully. Duration column's calculation like this.

avg(datediff(MINUTE, ei.SentDate, eo.SentDate)) over(partition by ei.mailbox) as DURATION   

回答1:


A google search landed me here http://www.sqlservercentral.com/Forums/Topic490411-8-1.aspx

and It says... which I just tested working ...

Declare @theMinutes int
Set @theMinutes = 67 

Select @theMinutes / 1440 as NoDays  -- 1440 minutes per day 
       , (@theMinutes % 1440) / 60 as NoHours -- modulo 1440 
       , (@theMinutes % 60) as NoMinutes -- modulo 60



回答2:


create FUNCTION  fun_Date_Friendly (@minutes int)
RETURNS nvarchar(100)
AS
BEGIN
   return CASE 
    when @minutes < 60 then cast( @minutes as varchar(10)) + ' Min'
    when @minutes < 1440 then cast(@minutes/60 as varchar(10)) + ' Hr, ' + cast(@minutes%60 as varchar(10)) + ' Min'
    else cast(@minutes/(1440 ) as varchar(10)) + ' Days, ' + cast((@minutes%1440 )/60 as varchar(10)) + ' Hr, ' + cast(((@minutes%1440 )%60) as varchar(10)) + ' Min'
    end
end
go

then just pass minutes to function

select  dbo.fun_Date_Friendly(20) val


来源:https://stackoverflow.com/questions/16352607/how-to-split-minutes-into-days-hours-and-minutes-in-tsql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!