【问题标题】:Return records from table where date column is between a second tables date column从日期列在第二个表日期列之间的表中返回记录
【发布时间】:2015-01-17 09:05:40
【问题描述】:

我对使用 sql 有疑问,我无法理解。

我有一个包含 2 列(in_time、out_time)和以下记录的主表(时钟)。

2017-01-17 06:00:00.000 to  2017-01-17 07:00:00.000
2017-01-17 09:00:00.000 to  2017-01-17 11:00:00.000
2017-01-17 17:00:00.000 to  2017-01-17 20:00:00.000

然后我有第二个查找表(班次),它也有 2 个日期时间列。 (shiftstart,shiftend)

2015-01-17 06:00:00.000 to 2015-01-17 16:00:00.000
2015-01-17 18:00:00.000 to 2015-01-17 23:00:00.000

我想要实现的是显示与我的主表 (clockins) 的总分钟差,其中 in_time 位于第二个表中的日期之间。

我尝试使用“between”进行子查询,但班次表有超过 1 条记录我必须检查。我尝试的另一个解决方案是在班次表上使用循环,然后仅使用基于班次表中每条记录的选择查询。这可行,但我可以看到这变得非常缓慢。

根据以上信息,应该返回时钟表的第 1 行和第 2 行,结果为 3 小时 = 180 分钟,并省略记录 2017-01-17 17:00:00.000

我希望这是有道理的。

【问题讨论】:

  • 您使用的是哪个 DBMS?后格雷斯?甲骨文?
  • 欢迎来到 StackOverflow!无需在标题中包含标签。请阅读meta.stackexchange.com/questions/19190/… 了解更多信息。
  • 两个表之间是否有共同的字段,比如shiftId
  • 是的,抱歉,这是一个错字 - 都是 2015 年的。我使用的是 MS SQL Server 2008。我会查看您的帖子并提供反馈。谢谢

标签: sql sql-server


【解决方案1】:

您没有指定您的 DBMS,但以下是标准 SQL(假设 out_time 和 in_time 确实是 timestamp 列)。结果会产生一个interval

select c.out_time - c.in_time as duration
from clockins c
  join shifts s on c.in_time between s.shiftstart and s.shiftend;

以上假设 2017 年是您的示例数据中的错字。如果您确实在时间戳中有不同的年份,并且您只是想要比较时钟的时间,那么您需要做这样的事情(再次强调:这是标准 SQL)

select c.out_time - c.in_time as duration
from clockins c
  join shifts s on cast(c.in_time as time) between cast(s.shiftstart as time) and cast(s.shiftend as time);

这将完全忽略时间戳的日期部分

SQLFiddle 示例:http://sqlfiddle.com/#!15/75a47/1

【讨论】:

    【解决方案2】:

    我认为您需要确定日期时间范围是否重叠。 如果两个表之间没有公共字段,请尝试以下操作:

    select Sum(DATEDIFF(hh, a.in_time, a.out_time)) as hoursWorkedThisShift
    from clockins a
    WHERE a.in_time <= '2015-01-17 16:00:00.000' and a.out_time >= '2015-01-17 06:00:00.000' 
    

    【讨论】:

    • 我不确定这是否有效。如果比较值确实是 1 条记录,那么就可以了。我需要比较的值在第二个表中,可能是 5 条左右的记录。
    • 我需要这样的东西 - select datediff(minute,in_time,out_tme)[my result] from dbo.clockins c where in_time >= (select ShiftStart from dbo.shifts) and in_time
    猜你喜欢
    • 1970-01-01
    • 2022-06-10
    • 2017-11-03
    • 2020-11-13
    • 2010-10-05
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多