sql - 如何在 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 Server。您可以通过计算列中使用的秒数来实现它datediff()
,然后将其添加到00:00:00.0000000
using 中dateadd()
。请注意,我不知道您的数据有多精确,所以如果您想让我更精确,您需要更改second
为milisecond
. 它是班次数据,因此不应超过 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
推荐阅读
- python - 为什么pygame在'__init__.py'中找不到引用'...'?
- aws-lambda - 用于 psycopg2 的 AWS Lambda 层
- c# - MongoClient 处理扩展的网络中断
- java - 如何从 HTTP 响应中获取 JSON 值?
- excel - 按字符拆分字符串并保留字符串前后
- java - Maven:如何配置 javadoc 以生成所有私有和包
- pgadmin-4 - dpkg 无法在我的 debian 上安装 pgAdmin4-web
- javascript - 使用 JavaScript 克隆 IList 中的项目
- c# - Razor Pages 保存日历中的点击日期
- javascript - 将无类型的 JavaScript 模块与 Typescript 一起使用:“未知”类型上不存在属性