为什么 Access 不能在表达式中正确解释这个时间范围?

Why isn't Access interpreting this time range correctly in an expression?

我正在为 MS Access 中的查询编写表达式。总体目标是创建一个新字段,承认仅仅因为第 3 班(晚上 10 点到早上 6 点)过了午夜,它应该仍然 return 他们开始的最初一天。我无法让它正常工作。

伪代码:

Date: IIF([RecordDate] has a time between 12:00AM and 6:00AM, return [RecordDate] - 1 day, [RecordDate])

实际代码

Date: IIf((Format([dbo_jobtran]![RecordDate], "Short Time") Between #00:00:00# And #6:00:00#),DateAdd("d",-1,Format([dbo_jobtran]![RecordDate],"Short Date")), [dbo_jobtran]![RecordDate])

输出(不正确)

RecordDate               Expression
8/10/2015 11:58:09 PM    8/10/2015
8/11/2015 12:07:52 AM    8/11/2015
8/11/2015 5:55:21 AM     8/11/2015
8/11/2015 6:17:06 AM     8/11/2015

预期输出

RecordDate               Expression
8/10/2015 11:58:09 PM    8/10/2015
8/11/2015 12:07:52 AM    8/10/2015
8/11/2015 5:55:21 AM     8/10/2015
8/11/2015 6:17:06 AM     8/11/2015

Format() returns 一个字符串值。尝试将字符串值与 Date/Time 值进行比较时,您的立场不稳。比较要求 Access 将其中一个值转换为另一个的数据类型。有时 Access 会正确处理(根据需要进行投射),但不要依赖于此。

检查您面临的问题的另一种方法是测试此查询:

SELECT Format(#8/11/2015 5:55:21#,"Short Time") Between #00:00:00# And #06:00:00# AS Expr2;

Expr2.

访问 returns 0(假)

始终使用 Date/Time 值与另一个 Date/Time 值进行比较:

SELECT
    j.RecordDate,
    IIf
        (
            TimeValue(j.RecordDate) Between CDate(0) And CDate(.25),
            DateValue(j.RecordDate) -1,
            DateValue(j.RecordDate)
        ) AS start_date
FROM dbo_jobtran AS j

备注:

  1. TimeValue returns 您的 Date/Time 值的时间部分和 returns 第 0 天的那个时间(1899 年 12 月 30 日)。在 Access 中没有诸如仅时间数据类型或仅日期数据类型之类的东西——我们只有 Date/Time.
  2. DateValue returns 从您的 Date/Time 值开始的日期,以午夜(凌晨 12 点)作为一天中的时间。
  3. CDate(0) 是 1899 年 12 月 30 日凌晨 12 点
  4. CDate(.25) 是 1899 年 12 月 30 日早上 6 点
  5. 如果您更喜欢 DateAdd,请在我使用 DateValue(j.RecordDate) -1
  6. 的地方替换为 DateAdd('d', -1, DateValue(j.RecordDate))