SQL - ISNULL或者如果不是最新日期

时间:2014-07-23 10:00:17

标签: sql date isnull

我有两个日期字段的情况。

如果一个是空的,那么拿另一个。目前,使用以下代码正常工作

select e.EMPLOY_REF, ISNULL(e.PROB_DOCS_SENT, ec.USR_FINALPROB)
from EMPLOYEE_TABLE e
join EMPLOYEE_USERCUST ec on ec.EMPLOY_REF = e.EMPLOY_REF

然而,可能是两者都被填满的情况,如果是,我需要将最新的日期作为有效日期。

如果两个日期都已填写,我如何确保它采用最新日期?

4 个答案:

答案 0 :(得分:0)

尝试以下操作 - 这适用于MSSQL

select e.EMPLOY_REF,  
case when   e.PROB_DOCS_SENT is null and ec.USR_FINALPROB is not null  then ec.USR_FINALPROB
    else   e.PROB_DOCS_SENT is not null and ec.USR_FINALPROB is null then e.PROB_DOCS_SENT
    else   e.PROB_DOCS_SENT is not null and ec.USR_FINALPROB is not null and e.PROB_DOCS_SENT >ec.USR_FINALPROB then e.PROB_DOCS_SENT
    else ec.USR_FINALPROB end
from EMPLOYEE_TABLE e
join EMPLOYEE_USERCUST ec on ec.EMPLOY_REF = e.EMPLOY_REF

答案 1 :(得分:0)

尝试以下查询,此解决方案的优势超过了解决方案是您可以使用更多列轻松扩展它的情况

SELECT EMPLOY_REF, MAX(Date)
FROM (
  select e.EMPLOY_REF, e.PROB_DOCS_SENT AS Date
  from EMPLOYEE_TABLE e
  join EMPLOYEE_USERCUST ec on ec.EMPLOY_REF = e.EMPLOY_REF
  union
  select e.EMPLOY_REF, ec.USR_FINALPROB AS Date
  from EMPLOYEE_TABLE e
  join EMPLOYEE_USERCUST ec on ec.EMPLOY_REF = e.EMPLOY_REF
) tbl
GROUP BY EMPLOY_REF

答案 2 :(得分:0)

试试这个:

SELECT 
   ID,
   CASE 
        WHEN Date1 > Date2 
        THEN Date1
        ELSE Date2
   END AS MostRecentDate
FROM Table

答案 3 :(得分:0)

您可以使用CASE-WHEN来处理所有可能的情况。如果两个日期都为空,则以下查询将今天的日期作为值。

select e.EMPLOY_REF, ISNULL(e.PROB_DOCS_SENT, ec.USR_FINALPROB)
case when e.PROB_DOCS_SENT is null and ec.USR_FINALPROB is null then getdate()
     when e.PROB_DOCS_SENT is null and ec.USR_FINALPROB is not null then ec.USR_FINALPROB
     when e.PROB_DOCS_SENT is not null and ec.USR_FINALPROB is null then e.PROB_DOCS_SENT
     when e.PROB_DOCS_SENT is not null and ec.USR_FINALPROB is not null 
     then 
         case when e.PROB_DOCS_SENT> ec.USR_FINALPROB then e.PROB_DOCS_SENT
              when e.PROB_DOCS_SENT> ec.USR_FINALPROB then ec.USR_FINALPROB
         end
end
from EMPLOYEE_TABLE e
join EMPLOYEE_USERCUST ec on ec.EMPLOY_REF = e.EMPLOY_REF