WHERE语句排除空值需要包含空值和失败的匹配

时间:2017-05-26 14:45:48

标签: sql

对于部件下面的代码,where语句的第二部分(after和)排除了d.CreditRating为null的所有内容。只需要c.ISIN,c.SEDOL,c.CUSIP中的一个来选择最近的日期并匹配该语句。如何将信用评级为空,因为我们无法匹配或实际值为空?

当只运行where语句中的所有内容时,查询才有效,但是它不会选择最近的日期。谢谢。

Select e.MSPortfolioId,
       b.PortfolioId,
       c.DetailHoldingTypeId,
       d.CreditRating,
       b.MarketValue,
       c.SecurityId,
       c.ISIN,
       c.SEDOL,
       c.CUSIP
From   PortfolioCoreData.dbo.LatestPortfolio e
Left Join HoldingData.dbo.HoldingDetail b
    On e.LatestStoredPortfolioId = b.PortfolioId
Left Join HoldingData.dbo.SecurityInfo c
    On b.SecurityId = c.SecurityId
Left Join BondData.dbo.BondCreditRating d
    On (Case When c.CUSIP Is Not Null Then c.CUSIP
             When c.ISIN Is Not Null Then c.ISIN
             Else c.SEDOL End) = d.BondId
Where  e.MSPortfolioId In ( '5670', '4404', '5973', '861996' )
       And (d.EffectiveDate = ( Select Max(d.EffectiveDate)
                                  From   BondData.dbo.BondCreditRating d
                                  Where  (Case When c.CUSIP Is Not Null Then c.CUSIP   When c.ISIN Is Not Null Then c.ISIN  When c.SEDOL Is Not Null Then c.SEDOL  End ) = d.BondId ));

1 个答案:

答案 0 :(得分:-1)

这是因为您的查询仅选择EffectiveDate,如果要添加EffectiveDate的值为null,您也需要询问它。

你可以尝试这个

Where  e.MSPortfolioId In ( '5670', '4404', '5973', '861996' )
       And 
       (
        (d.EffectiveDate = (
                                  Select Max(d.EffectiveDate)
                                  From   BondData.dbo.BondCreditRating d
                                  Where  (Case When c.CUSIP Is Not Null Then c.CUSIP
                                               When c.ISIN Is Not Null Then c.ISIN
                                               When c.SEDOL Is Not Null Then c.SEDOL
                                          End
                                         ) = d.BondId
                              )
           ) OR d.EffectiveDate is null);