IIF条件StartDate EndDate int / date碰撞

时间:2014-09-03 20:36:15

标签: tsql sql-server-2012

我正在尝试使用SS-2012中的IIF语句

我有这个工作正常

SELECT 
       NULLIF(IIF( a.EndDate is null
                , DATEDIFF(MONTH, a.StartDate, getdate()) ,
       IIF( a.EndDate is not null
                ,  DATEDIFF(MONTH, a.StartDate, a.EndDate) , '')),'') 
       AS Months
      ,NULLIF(IIF( a.EndDate is null
                , DATEDIFF(Day, a.StartDate, getdate()) ,
       IIF( a.EndDate is not null
                ,  DATEDIFF(Day, a.StartDate, a.EndDate) , '')),'') 
       AS DateDays

  FROM
       TableDates a

我遇到的问题是开始日期和结束日期是否在同一天(我试图将其默认为1个月,无论月份是30天或31天)

我快乐了

int is incompatible with date 

在下面尝试时

   ,NULLIF(
    IIF ( (a.EndDate is null)  , DATEDIFF(Day, a.StartDate, getdate()) ,
    IIF ( (a.StartDate = a.EndDate) 
          , DATEADD(Day, DATEDIFF(Day, a.StartDate, a.EndDate), a.EndDate),
      IIF ( (a.EndDate is not null) , DATEDIFF(Day, a.StartDate, a.EndDate),'')

          )),'')

如果日期相同,我如何将天数默认为30-31,将月份默认为1?

1 个答案:

答案 0 :(得分:1)

如果您需要将当月的天数显示为默认,其中开始日期和结束日期在同一天,那么我希望以下查询对您有用

IIF ( (a.StartDate = a.EndDate),
    (datediff(day, a.StartDate, dateadd(month, 1, a.StartDate))),...

并将月份显示为默认,其中开始日期和结束日期在同一日期

IIF ( (a.StartDate = a.EndDate),Month(a.StartDate),...