如果field = Null则使用不同的字段

时间:2014-12-29 12:19:15

标签: sql select if-statement where datediff

我已经编写了一些Sql代码,通过使用dateOffered字段显示所有客户的提议即将在未来90天内到期。但是,数据库中有另一个名为OfferExpirydate的字段,我会使用此字段,但它并不总是填写。

我的问题是我希望代码查看OfferExpirydate,如果它有值,则使用它,否则使用Dateoffered字段作为我的代码在stats下面。 (如果未填写OfferExpirydate,则将其设置为NULL) 任何有关这方面的帮助都非常感谢

SELECT      
DateOffered,
      pr.ClientID,
      pr.id AS profileID,
      cf.Clntnme,
      pm.Lender,
      ABS(DATEDIFF(DAY, DateOffered, DATEADD(d,-90, GETDATE()))) AS 'NoOfDays'
FROM tbl_profile AS pr 
INNER JOIN tbl_Profile_Mortgage AS pm
      ON pr.id = pm.fk_profileID
INNER JOIN dbo.tbl_ClientFile AS cf
      ON pr.ClientID = cf.ClientID
WHERE 
DateCompleted IS NULL AND
DateOffered >  DATEADD(d,-90, GETDATE())
AND DATEDIFF(DAY, DateOffered, DATEADD(d,-90, GETDATE())) > -15
ORDER BY DateOffered ASC

2 个答案:

答案 0 :(得分:2)

COALESCE(col1, col2, ...)

将选择第一个非空值。

答案 1 :(得分:1)

试试这个:

SELECT DateOffered,
       pr.ClientID,
       pr.id AS profileID,
       cf.Clntnme,
       pm.Lender,
       ABS(DATEDIFF(DAY, DateOffered, DATEADD(d,-90, GETDATE()))) AS 'NoOfDays'
FROM tbl_profile AS pr 
INNER JOIN tbl_Profile_Mortgage AS pm
      ON pr.id = pm.fk_profileID
INNER JOIN dbo.tbl_ClientFile AS cf
      ON pr.ClientID = cf.ClientID
WHERE DateCompleted IS NULL AND 
1 = CASE WHEN OfferExpirydate IS NOT NULL AND DATEDIFF(DAY, OfferExpirydate, GETDATE()) > -15 THEN 1 
        WHEN DateOffered >  DATEADD(d,-90, GETDATE()) AND DATEDIFF(DAY, DateOffered, DATEADD(d,-90, GETDATE())) > -15 THEN 1 
        ELSE 0
    END
ORDER BY DateOffered ASC