时间跨过午夜时的 Datediff
知道如何构建 datediff 查询来计算可能跨越午夜的时间吗?
当然,如果是一种情况,我会分别计算午夜和午夜的部分,但我需要通用查询,因为我有数千行,其中一些跨越午夜,有些则不跨越午夜,对于每一行我必须计算。 datediff(最多 10 分钟,不能跨越 2 天)。
Any idea how to build datediff query that calculate time that possibly crosses midnight?
Of course, if that is one case, I would calculate separately part to and from midnight, but I need universal query, because I have thousands of rows, where some of them crosses midnight, and some not, and for every one of them I have to calc. datediff (which is up to 10 minutes, can't cross 2 days for that matter).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
DATEDIFF 函数可以处理这两种情况。
The DATEDIFF function handles both cases.
假设开始工作 = 20:00:00
假设 end_work = 06:00:00
答案 = 08:00:00
选择*,
案例
当结束工作>开始工作
然后 timediff(end_work, begin_work)
ELSE addtime(timediff('24:00:00',begin_work),end_work)
END AS elapsed_time
FROM my_table
限制 - 这只适用于不超过 23h 59m 59s 的持续时间。
如果持续时间超过 24 小时,我建议使用 DATEDIFF
希望这会有所帮助,
麦克风
Assume begin_work = 20:00:00
Assume end_work = 06:00:00
ANSWER = 08:00:00
SELECT *,
CASE
WHEN end_work > begin_work
THEN timediff(end_work, begin_work)
ELSE addtime(timediff('24:00:00',begin_work),end_work)
END AS elapsed_time
FROM my_table
Limitation- this will only work for a time duration that does not exceed 23h 59m 59s.
If a time duration is over 24hrs I suggest using a DATEDIFF
Hope this helps,
Mike
您看到的问题是由于 datediff 函数查看值所致:
分钟值确实发生了变化。它从 59 换行到 00,因此函数正确返回 1。为了正确计算经过的时间,我使用秒除以 60 表示分钟,使用毫秒除以 1000 表示秒。这可以防止穿越午夜问题。 (注意:3 毫秒是 SQL Server 中时间的最小粒度)
The problem you are seeing is due to the datediff function looking at the values:
The minute value does change. It wraps from 59 to 00 so the function correctly returns 1. To correctly calculate elapsed time I use seconds divided by 60 for minutes and milliseconds divided by 1000 for seconds. This prevents the crossing midnight issue. (note: 3 milliseconds is smallest granularity for time in SQL Server)