T-SQL Format seconds as HH:MM:SS time

放肆的年华 提交于 2020-12-03 07:26:31

问题


Is there any tricky way to format seconds like hours:minutes:seconds. For example,

3660

seconds will be displayed as

01h 01m 00s

or

01:01:00

I am aware of the standard way of doing this:

  1. Divide all seconds on 3600 to get the hours
  2. Divide the rest seconds on 60 to get the minutes
  3. The rest are the seconds

I met the following issues:

  1. I am not able to create separate function that do this.

  2. My code is in view using several CTEs. So, variables can be declare using the CTEs only.

  3. I am not able to use the standard solution because I will have results bigger then one day - How to convert Seconds to HH:MM:SS using T-SQL

回答1:


SELECT CONVERT(VARCHAR(10),Seconds/3600)  
    +':' 
    + RIGHT('00'+CONVERT(VARCHAR(2),(Seconds%3600)/60),2) 
    +':' 
    + RIGHT('00'+CONVERT(VARCHAR(2),Seconds%60),2) AS [HH:MM:SS] 
FROM table1

See this SQLFiddle




回答2:


Try this:

SELECT CONVERT(TIME(0), DATEADD(SS,***seconds***,0),108) as 'FieldName'

will return HH:MM:SS

Example:

46800 seconds = 1:00 PM

FieldName = 13:00:00

Hope this helps.




回答3:


SELECT cast(seconds/3600 as varchar(6)) +
right(cast(dateadd(second, seconds,0) as time(0)), 6)
FROM <yourtable>


来源:https://stackoverflow.com/questions/13177192/t-sql-format-seconds-as-hhmmss-time

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