【问题标题】:Finding the latest date of 2 date columns in SQL在 SQL 中查找 2 个日期列的最新日期
【发布时间】:2013-12-06 15:02:43
【问题描述】:

我无法找到以下 SQL 查询的解决方案:

我有一个包含 2 个日期列的表:PurchaseDateRefundDate

我有一个 StartDateEndDate 来定义查询的日期范围。

我想通过PurchaseDateRefundDate 来限制查询,以最早为准。任何一个日期都可以为空。

因此,如果 PurchaseDate 是 18.Nov.2013 并且 RefundDate 是 03.Dec.2013 那么我想在 where 子句中使用 PurchaseDate 来限制 startDateEndDate 内的结果集

另一个例子是,如果 PurchaseDate 是 01.Aug.2013 并且 RefundDate 是 19.May.2013 那么我想在 where 子句中使用 RefundDate。

这是我到目前为止所得到的,但它不正确,我需要选择两个日期中最早的一个来限制 where 子句:

SELECT OrderID, AddressID, PurchaseDate, RefundDate
FROM
Orders
WHERE
(PurchaseDate IS NOT NULL AND PurchaseDate >= @queryStartDate 
   AND  PurchaseDate <= @queryEndDate) OR
 (RefundDate IS NOT NULL AND RefundDate >= @queryStartDate 
       AND  RefundDate <= @queryEndDate)

我考虑过使用COALESCE,但这不起作用,因为它只会选择第一个非空日期而不是最早的日期。

我想我将不得不做两个查询并将它们合并,但感觉有更好的方法,我可以通过一个查询和 where 子句中的一些巧妙的魔法来做到这一点......

【问题讨论】:

  • 您使用的是哪个 DBMS?
  • 对不起 - SQLServer 2012 - 刚刚为它添加了一个标签
  • 我想知道为什么这个问题被否决了?

标签: sql date sql-server-2012


【解决方案1】:

您可以通过在逻辑中使用附加子句来做到这一点:

SELECT OrderID, AddressID, PurchaseDate, RefundDate
FROM Orders o
WHERE (PurchaseDate IS NOT NULL and
       PurchaseDate <= coalesce(RefundDate, PurchaseDate) and
       PurchaseDate between @queryStartDate AND @queryEndDate
      ) or
      (RefundDate IS NOT NULL and
       RefundDate <= coalesce(PurchaseDate, RefundDate and
       RefundDate between @queryStartDate AND @queryEndDate
      );

如果您在列上有索引,union 方法可能会更快(即使消除重复)。

【讨论】:

    【解决方案2】:

    case 是你的朋友...而不是合并,写

     case when PurchaseDate < RefundDate 
           then PurchaseDate else RefundDate end
    

    因此,您的查询变为:

     SELECT OrderID, AddressID, PurchaseDate, RefundDate
     FROM Orders
     WHERE case when PurchaseDate < RefundDate 
                then PurchaseDate else RefundDate end 
           Between @queryStartDate And @queryEndDate
    

    【讨论】:

      【解决方案3】:

      我认为这就像使用最小函数一样简单。

      SELECT OrderID, AddressID, PurchaseDate, RefundDate
      FROM Orders
      WHERE least( PurchaseDate , RefundDate ) Between @queryStartDate And @queryEndDate
      

      【讨论】:

      • 这个想法可能很好,但如果其中一个为空,你就有麻烦了。
      • 可能是COALESCEleast内的日期。
      • 对不起,我最初没有指定 DBMS (SQL Server2012)。我认为 LEAST 只是 Oracle,不是吗?
      猜你喜欢
      • 2020-04-28
      • 1970-01-01
      • 2012-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-23
      相关资源
      最近更新 更多