将时间戳细分为3个时隙
我遇到以下问题,我必须将不同的事务分组到时隙中。假设您有一个表,其中的记录包含条目日期时间戳。这些记录是由不同班次的用户(操作员)创建的
Shift 1:5 - 13h // 班次 2:13 - 21 小时 // 班次 3:21 - 5 小时
现在我想要一个灵活的查询,将时间戳向下舍入到班次的开始时间。示例:
2010-09-08 06:12:00.000 --> 2010-09-08 05:00:00.000
2010-09-08 02:12:00.000 --> 2010-09-07 21:00:00.000
我已经使用 dateadd 和 datediff 尝试了一些查询,但我没有让它工作......任何人都可以帮忙吗?谢谢
I have following problem where I have to group different transactions into timeslots. Suppose you have a table with records which contain an entry datetimestamp. These records are created by users (operators) who work in different shifts
Shift 1: 5 - 13h //
Shift 2: 13 - 21h //
Shift 3: 21 - 5h
Now I want to have a flexible query which rounds the timestamps down to the start time of the shift. Example:
2010-09-08 06:12:00.000 --> 2010-09-08 05:00:00.000
2010-09-08 02:12:00.000 --> 2010-09-07 21:00:00.000
I already tried a few queries using dateadd and datediff but I don't get it to work... Can anybody help? Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您的数据库支持 INTERVAL 类型,请从事件的时间戳中减去 5 小时,将其相对于午夜(而不是 0500)排列,并将时间部分除以 8 小时以获得从零开始索引的轮班编号。
要获得轮班开始时间,请将轮班数乘以八小时,将其添加到上面所做的减法的日期部分,然后再加上五个小时,使其与轮班时间表保持一致。
如果您要经常查询这些数据,您可能最好创建第二个表,通过 ID 及其开始时间单独标识每个班次。然后,您可以在包含事件的表上使用 ON INSERT 触发器来填充班次表,该触发器执行一次计算,根据需要将新行插入到班次表中,并使用外键将事件行与其关联。这也将为您提供一种更简单的方法来查询特定轮班期间发生的所有事件。
If your database supports an
INTERVAL
type, subtract five hours from the event's timestamp to line it up relative to midnight instead of 0500 and divide the time part by eight hours to get a shift number indexed from zero.To get the shift start time, multiply the shift number by eight hours, add that to the date part of the subtraction you did above and then add five additional hours to line it back up with your shift schedule.
If you're going to be querying these a lot, you might be better off to create a second table that individually identifies each shift by an ID and its start time. You can then populate the shifts table using an ON INSERT trigger on the table containing your events that does the calculation once, inserts a new row into the table of shifts if needed and ties your event row to it using a foreign key. That would also give you a much easier way to query all of the events that happened during a specific shift.
这个怎么样...?
How about this...?