2017-04-01 99 views
1

我有两列:rental_dateactual_retdate。我需要找到actual_retdaterental_date之间的天数。对于某些情况,actual_retdate可能为空,因此我希望在这些情况下找到今天的日期和租赁日期之间的天数。在两个日期之间使用空值查找SQL Days

目前我有:

select rental_date, actual_retdate, actual_retdate - rental_date as 'Daysbetween' 
from rental_agreement 

这给我的答案:

 
Rental_date  actual_retdate Daysbetween 
2014-07-04 2014-07-11 7 
2016-05-06 2016-05-08 2 
2016-08-07 2016-09-07 100 
2015-02-02 2015-02-10 8 
2015-10-10 2015-10-15 5 
2015-08-07 2015-08-17 10 
2017-02-04 NULL   NULL 
2016-07-08 2016-07-16 8 
2017-03-02 NULL   NULL 
2015-03-15 2015-04-15 100 
+0

在MySQL中,减法运算符不保证在两个日期值之间返回一个数字天。它在某些情况下可能有效(当两个日期在相同的年份和月份),但在更一般的情况下不会返回正确的值。 (请注意返回'100'的行。在MySQL中,我们可以使用'TIMESTAMPDIFF(DAY,dateexpr1,dateexpr2)'来获得天数的差异。 – spencer7593

回答

1

使用COALESCE为案件提供了另一种价值,当值NULL

SELECT 
    rental_date, 
    actual_retdate 
    COALESCE(actual_retdate, CURDATE()) AS actual_retdate_or_today, 
    COALESCE(actual_retdate, CURDATE()) - rental_date AS days_between 
FROM 
    rental_agreement 

CURDATE()返回当前日期。我认为actual_retdatedate列而不是datetime列,因为结果可能是意外的。另请考虑使用DATEADD而不是-运算符来执行日期算术计算。

我重复COALESCE(actual_retdate, CURDATE())表达式的原因是因为在SQL中不能在另一列中引用列表达式 - 您必须重新计算结果或将其包装在外部查询中。

1

您正在寻找coalesce()

select rental_date, actual_retdate, 
     coalesce(actual_retdate, curdate()) - rental_date as Daysbetween 
from rental_agreement 
2

听起来像是你可以合并与actual_retdate NOW()。

它看起来是这样的:

SELECT rental_date, 
    actual_retdate, 
    COALESCE(actual_retdate,NOW()) - rental_date as 'Daysbetween' 
FROM rental_agreement 

COALESCE基本上返回列表中的第一个非空值。所以如果actual_retdate为NULL,它将返回NOW()的值。

https://dev.mysql.com/doc/refman/5.7/en/comparison-operators.html#function_coalesce


编辑:由于斯宾塞提到减法不是作为一种方式来获得的天数之差完全可靠的,这里是用他建议的TIMESTAMPDIFF更新的片段。

SELECT rental_date, 
    actual_retdate, 
    TIMESTAMPDIFF(DAY,COALESCE(actual_retdate,NOW()),rental_date) as 'Daysbetween' 
FROM rental_agreement 
相关问题