【问题标题】:Difference between two dates and if one date is null use current day in SQL两个日期之间的差异,如果一个日期为空,则在 SQL 中使用当前日期
【发布时间】:2017-02-11 00:18:45
【问题描述】:

我必须找出两个合同日期之间的差异。基本上在生效日期和结束日期之间。但是如果合同仍然有效,所以我想要今天。(时间戳)?我如何在 SQL 中结合两者 例如:

start d: 1/1/17 end date: 2/1/17 effective days 31
start d: 1/1/17 end date: null  effective days: total days to date.

【问题讨论】:

  • DATEDIFF(DAY,StartDate,ISNULL(EndDate,GETDATE())

标签: sql sql-server time


【解决方案1】:
SELECT DATEDIFF( day, 
                 [start], 
                 COALESCE ([end], GETDATE())
               )

【讨论】:

  • COALESCE 只有一个L
  • sql server 银徽章 :)
  • 恭喜获得 SQL Server 徽章——当之无愧的成就。
  • 谢谢 Juan,但是 SQL 怎么知道为空值选择 GETDATE
  • COALESCE 工作,该函数返回第一个非空值。在这种情况下,如果第一个值为 NULL,则使用第二个。
【解决方案2】:

您可以使用case 表达式将值相互比较,然后使用getdate() 等函数返回当前日期和时间。

select getdate()           -- Will return the date and time of right now

      ,case when 1 < 2
            then 'Less'
            else 'Greater'
            end            -- This will return the value 'Less'

      ,case when YourDateField < getdate()
            then YourDateField
            else getdate()
            end            --  This will return the earliest of YourDateField or right now

在简单地检查值是否为null 时,不要使用稍微冗长的case,您还可以使用isnullcoalesce 这两个速记函数之一。 isnull 只检查一个值,coalesce 从列表中返回第一个不是 null 的值(还有其他差异,但我会留给你研究):

select isnull(YourPopulatedDateField,getdate())              -- Will return YourPopulatedDateField
      ,isnull(YourNullDateField,getdate())                   -- Will return right now

      ,coalesce(YourNullDateField,getdate())                 -- Will return right now
      ,coalesce(YourNullDateField,OtherNullField, getdate()) -- Will also return right now

将其中之一与datediff 函数结合起来,可以为您提供其他 cmets 和答案所提供的内容:

-- Both of these will return the same result:
select datediff(day,
               ,StartDate
               ,coalesce(EndDate, getdate())
               )

      ,datediff(day,
               ,StartDate
               ,isnull(EndDate, getdate())
               )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-12
    • 2015-06-21
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    • 2018-10-25
    相关资源
    最近更新 更多