WHERE语句不包含空值需要包含空值和失败的匹配
问题描述:
对于下面的代码,where语句的第二部分(after和)将排除d.CreditRating为空的所有内容。该声明需要选择最近的日期并且仅通过c.ISIN,c.SEDOL,c.CUSIP中的一个来匹配。如何使信用评级为空,因为我们无法匹配或实际值为空?WHERE语句不包含空值需要包含空值和失败的匹配
该查询只在运行where语句前的所有内容以及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));
答
发生这种情况是因为您的查询选择只有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);
+0
尽管这有效,但它仍然不是一个好的答案。这是一个连接条件,因此应该在'ON'子句中。那么'OR d.EffectiveDate为空'就没有必要了。 –
它不包括空值,因为'WHERE'语句执行*之后*了'LEFT JOIN'。如果你想保留'OUTER JOIN'的NULL值,你需要在'ON'子句中包含这些条件。 – Siyual
向我们展示数据库模式,样本数据和预期输出。 \t请阅读[**如何提问**](http://stackoverflow.com/help/how-to-ask) \t \t这里是一个伟大的地方[** START **] (http://spaghettidba.com/2015/04/24/how-to-post-at-sql-question-on-a-public-forum/)来了解如何提高您的问题质量并获得更好的答案。 \t [**如何创建一个最小,完整和可验证示例**](http://stackoverflow.com/help/mcve) –
顺便说一句:'当c.CUSIP不是空的情况下,然后c.CUSIP当c.ISIN不为空然后c.ISIN当c.SEDOL不是空然后c.SEDOL End'就是'COALESCE(c.CUSIP,c.ISIN,c.SEDOL)'。 –