如何减去两个日期时间值并在 SQL 服务器中获得 HH:MM:SS 格式的输出?
How to subtract two datetime values and get the output in HH:MM:SS format in SQL Server?
我想减去两个日期时间值并以 HH:MM:SS 格式输出。
如果相差超过 1 天,则需要将天数加到小时数上。
我尝试按如下所述连接 datediff 输出
select concat(datediff(hh, '2019-07-16 04:45:03.000','2019-07-17 19:38:13.000')
,':',
(datediff(mi, '2019-07-16 04:45:03.000','2019-07-17 19:38:13.000') -(datediff(hh, '2019-07-16 04:45:03.000','2019-07-17 19:38:13.000')*60))
,':',
(datediff(ss, '2019-07-16 04:45:03.000','2019-07-17 19:38:13.000')-(datediff(mi, '2019-07-16 04:45:03.000','2019-07-17 19:38:13.000')*60)))
预期输出:38:53:10
实际输出:39:-7:10
你能告诉我我犯了什么错误吗?有没有更好的方法来获得所需的输出?
类似于:
with q as
(
select datediff(SECOND, '2019-07-16 04:45:03.000','2019-07-17 19:38:13.000') secs
), hms as
(
select secs/60/60 as hours, (secs/60) % 60 as minutes , secs % 60 seconds
from q
)
select concat(format(hours,'00'),':',format(minutes,'00'),':',format(seconds,'00') ) hms
from hms
哪个returns
38:53:10
我想减去两个日期时间值并以 HH:MM:SS 格式输出。
如果相差超过 1 天,则需要将天数加到小时数上。
我尝试按如下所述连接 datediff 输出
select concat(datediff(hh, '2019-07-16 04:45:03.000','2019-07-17 19:38:13.000')
,':',
(datediff(mi, '2019-07-16 04:45:03.000','2019-07-17 19:38:13.000') -(datediff(hh, '2019-07-16 04:45:03.000','2019-07-17 19:38:13.000')*60))
,':',
(datediff(ss, '2019-07-16 04:45:03.000','2019-07-17 19:38:13.000')-(datediff(mi, '2019-07-16 04:45:03.000','2019-07-17 19:38:13.000')*60)))
预期输出:38:53:10
实际输出:39:-7:10
你能告诉我我犯了什么错误吗?有没有更好的方法来获得所需的输出?
类似于:
with q as
(
select datediff(SECOND, '2019-07-16 04:45:03.000','2019-07-17 19:38:13.000') secs
), hms as
(
select secs/60/60 as hours, (secs/60) % 60 as minutes , secs % 60 seconds
from q
)
select concat(format(hours,'00'),':',format(minutes,'00'),':',format(seconds,'00') ) hms
from hms
哪个returns
38:53:10