SQL发现午夜过去的时间重叠(跨越2天)
我知道有很多此类问题,但我没有看到与我的标准足够相似的问题。所以我想请求你的帮助。我拥有的字段只是时间类型的开始和结束。我不能在此提及任何具体日期。如果时间范围没有跨过午夜,我只会比较两个元组:(
end1 > start2 AND start1 < end2
端点接触不被认为是重叠的。)
但是当我涉及经过(或在)午夜的时间范围时,这显然不起作用。例如,给定:
start | end
--------+--------
06:00PM | 01:00AM
03:00PM | 09:00PM
在不涉及日期的情况下,我该如何实现这一目标。我的假设是,如果结束时间小于开始时间,那么我们将涉及 2 天。
我试图用简单的标准 SQL 来完成此操作,因此只需在 WHERE 子句中使用简单而简洁的逻辑即可。
谢谢大家!
补充:
另外,我如何测试一个时间范围是否完全包含另一个时间范围?再次感谢!
I know there are lots of these types of questions, but i didn't see one that was similar enough to my criteria. So i'd like to ask for your help please. The fields i have are just start and end which are of time types. I cannot involve any specific dates in this. If the time ranges don't go pass midnight across day, i'd just compare two tuples as such:
end1 > start2 AND start1 < end2
(end points touching are not considered overlapped here.)
But when I involve time range that pass (or at) midnight, this obviously doesn't work. For example, given:
start | end
--------+--------
06:00PM | 01:00AM
03:00PM | 09:00PM
Without involving dates, how can i achieve this, please. My assumption is, if end is less than start, then we're involving 2 days.
I'm trying to do this in plain standard SQL, so just a simple and concise logic in the WHERE clause.
Thank you everyone!
Added:
Also, how would I test if one time range completely envelopes another? thanks again!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您的 SQL 支持时差:
If your SQL supports time differences:
不幸的是,“普通”SQL 过于笼统,无法用于实际数据库。原因是各种数据库产品对计算两个时间之间的持续时间的支持程度不同。例如,在 SQL Server 2008 中,将时间值转换为
DateTime
然后进行比较会简单得多,因为 Time 数据类型不支持许多比较运算符。Unfortunately, "plain" SQL will be too general to use against an actual database. The reason is that the various database products have different levels of support for calculating the duration between two times. For example, in SQL Server 2008, it would be substantially simpler to convert the time values to
DateTime
and then do the comparison since many comparison operators are not supported on the Time data type.使用开始时间和持续时间(以分钟或任何合适的单位为单位)
use start time and duration (in minutes or whatever unit is appropriate)
程序 Transtar 遇到了这个问题。时间数据不与任何日期关联,日期时间字段中的时间数据也不关联。该计划最初设计为发布从凌晨 4 点到午夜左右的公交行程,只要公交不是全天候运行,就可以正常运行。我构建了一个对时间进行滑动测试的函数,这样如果您要求凌晨 5 点,它会查看从凌晨 1 点到凌晨 12:59 的时间。我用 FORTRAN 写的,但无论语言如何,算法都是相同的。
The program Transtar had this problem. The time data was not associated with any date, nor was the time data in a date time field. The program initially was designed to issue transit itinaries from about 4AM to midnight which worked fine as long as the transit wasn't around the clock. I built a function which did a sliding test for the times so that if you asked for 5AM it would look at times from 1AM to 12:59AM. I wrote it in FORTRAN, but the algorythm would be the same regardless of language.