【问题标题】:Why do I get different results with this SQL Date Part and date parameters为什么我使用此 SQL 日期部分和日期参数会得到不同的结果
【发布时间】:2015-04-02 18:56:00
【问题描述】:

当我在我的表上运行这个 where 子句时,我得到了 2 个不同的结果,在我看来,我应该得到相同数量的记录。

我只使用一个静态日期进行测试,另一个也应该检索到我试图获得上个月结果的相同结果

我认为查询是一个会自动加载前几个月记录的报告。

WHERE        
    (OrderReceiptedDate >= '2015-03-01') 
    AND (OrderReceiptedDate <= '2015-03-31')

WHERE
    (DATEPART(mm, OrderReceiptedDate) = DATEPART(mm, DATEADD(mm, - 1, GETDATE()))) 
    AND 
    (DATEPART(yy, OrderReceiptedDate) = DATEPART(yy, DATEADD(mm, - 1, GETDATE())))

【问题讨论】:

  • 你应该在两个日期之间使用
  • 哪个 dbms? (您正在使用产品特定的功能。)

标签: sql datepart


【解决方案1】:

这是两条语句

WHERE (OrderReceiptedDate >= '2015-03-01' AND
       OrderReceiptedDate <= '2015-03-31'
      )

WHERE (DATEPART(month, OrderReceiptedDate) = DATEPART(month, DATEADD(month, - 1, GETDATE()))) AND
      (DATEPART(year, OrderReceiptedDate) = DATEPART(year, DATEADD(month, - 1, GETDATE())))

鉴于今天是 2015 年 4 月,您预计这两个都将获得 3 月的所有日期。而且,如果您的日期没有时间成分,他们会这样做。问题是 3 月 31 日的几乎任何日期时间都不符合第一个条件。一个例外恰好是在午夜:2015-03-01 00:00:00.000。

第一个最好写成:

WHERE (OrderReceiptedDate >= '2015-03-01' AND
       OrderReceiptedDate < '2015-04-01'
      )

写“找我上个月的日期”的更好方法是:

WHERE OrderReceiptedDate >= dateadd(month, -1, cast(getdate() - day(getdate()) + 1 as date)) and
      OrderReceiptedDate < cast(getdate() - day(getdate()) + 1 as date)

这会在getdate() 上进行所有计算,因此查询仍然可以利用OrderReceiptDate 上的索引。

【讨论】:

    猜你喜欢
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-06
    • 2020-02-10
    • 2019-07-23
    相关资源
    最近更新 更多