需求:在使用报表工具时,经常使用时间统计,有时候需要统计秒数,有时候需要显示为时:分:秒的格式,在mysql中,如何把秒数转为时:分:秒样式呢,主要的方式有两种,一是利用mysql的内置函数sec_to_time(),另外一种是通过floor()函数和字符串拼接函数concat()进行拼接,该方式需要考虑时,分,秒小于10的情况,需要补0显示;具体方式如下:
方式一:利用mysql的内置函数
|
TIME_FORMAT(sec_to_time(sum(run_time)),'%H:%i:%s') as totaltimes ; |
注意:time_format()是把时间格式转为字符串函数,如果直接使用sec_to_time(),部分报表工具不支持,必须通过time_format()转化为字符串即可。sec_to_time()函数最大范围(即838:59:59),字符串拼接方式则不受限制。
方式二:利用字符串拼接方式
|
Select CONCAT( case when FLOOR( sum(run_time)/ 3600 )<10 then concat('0',FLOOR( sum(run_time)/ 3600 )) else FLOOR( sum(run_time)/ 3600 ) end , ':', case when FLOOR(( sum(run_time)% 3600 )/ 60 ) <10 then concat('0',FLOOR(( sum(run_time)% 3600 )/ 60 )) else FLOOR(( sum(run_time)% 3600 )/ 60 ) end , ':', case when (sum(run_time)% 60) < 10 then concat('0',sum(run_time)% 60) else sum(run_time)% 60 end ) as totaltimes From dual; |
说明:
一、SEC_TO_TIME()函数
1.该函数接受的参数必须是一个整数(INT或BIGINT类型),表示秒数。
2.返回的时间是基于24小时制的。
3.如果输入的秒数非常大,超过了mysql中TIME类型能表示的最大范围(即838:59:59),SEC_TO_TIME()函数将返回一个错误。
二、TIME_FORMAT函数
TIME类型用于存储时间,格式为’HH:MM:SS’。如果我们想将TIME类型的数据转换为字符串形式,可以使用TIME_FORMAT函数。该函数接受两个参数,个参数为时间列或表达式,第二个参数为转换格式。
1万+

被折叠的 条评论
为什么被折叠?



