首页 > 解决方案 > 如何在 SQL 中将两个时间值相加

问题描述

我有一张桌子'accumulate_low_risk''accumulate_high_risk'。两者都是timedata (time(7))格式00:00:00.0000000

我想将它们加在一起并将它们放入另一个名为“combined_shift_total”的时间数据中

我试图将它们转换为秒,将结果加在一起并将它们转换回时间数据,但我迷路了。

表格如下:

CREATE TABLE accumulate_time ('id INT IDENTITY(1,1) PRIMARY KEY,time DATETIME NOT NULL,worker_id INTEGER NOT NULL REFERENCES worker_table(worker_id),shift_start DATETIME NOT NULL,accumulate_low_risk TIME NOT NULL,accumulate_high_risk TIME NOT NULL,combined_shift_total TIME NOT NULL)

我正在尝试类似的东西......

select Sum(Left (CONVERT(nvarchar(30),accumulate_low_risk, 126),2) * 3600 + substring(accumulate_low_risk, 4,2) * 60 + substring(accumulate_low_risk, 7,2))
from accumulate_time WHERE id IN (SELECT max(id) FROM accumulate_time WHERE worker_id = 6)

但这太乱了。

我对 SQL 的了解有限,所以我确信有一种简单的方法可以实现这一点。

我将非常感谢任何和所有的帮助。

谢谢!

标签: sql

解决方案


对我来说,它看起来像 SQL Server。您可以通过计算列中使用的秒数来实现它datediff(),然后将其添加到00:00:00.0000000using 中dateadd()。请注意,我不知道您的数据有多精确,所以如果您想让我更精确,您需要更改secondmilisecond. 它是班次数据,因此不应超过 24 小时,但请注意在这种情况下它不起作用。

select cast(dateadd(second, datediff(second, '00:00:00.0000000', accumulate_low_risk) + datediff(second, '00:00:00.0000000', accumulate_high_risk), '2019-01-01') as time(7))
from accumulate_time 

一个例子它是如何在临时表上工作的:

create table #time (t1 time(7), t2 time(7))
insert into #time values ('01:12:04.0000000','00:12:04.0000000')

select cast(dateadd(second, datediff(second, '00:00:00.0000000', t1) + datediff(second, '00:00:00.0000000', t2), '2019-01-01') as time(7))
from #time

推荐阅读