SQL - 如何在使用MAX()函数时包含NULL值?

时间:2017-08-31 21:02:45

标签: sql-server null max aggregate-functions where-clause

我正在尝试创建一个报告,其中只显示最新的CoverageGroup,包括空值。

Sample - Current VS Want

这是当前代码(没有MAX()函数):

SELECT
    p.AcctNumber,
    c.sDate,
    ISNULL(cv.Coveragegroup,0) AS [CoverageGroup],
    wd.Code,
    ISNULL(CO2.lname,'Patient') AS [PrimIns],
    p.DefaultCoverageGroup,
    ISNULL(cv.LevelOfCoverage,0) AS [LevelOfCoverage]
FROM 
    Patient p
FULL OUTER JOIN 
    Charge c ON c.PatientID = p.IDPatient
FULL OUTER JOIN 
    Coverage cv ON cv.PatientiD = p.IDPatient
FULL OUTER JOIN 
    WorkDescriptor wd ON wd.IDWorkdescriptor = c.WorkDescriptorID
FULL OUTER JOIN 
    InsCompany ic on ic.IDInsCompany = cv.InsCompanyID
FULL OUTER JOIN 
    Contact co2 on co2.IDContact = ic.ContactID
WHERE 
    p.AcctNumber IN (256500, 256569)
    AND (cv.Coveragegroup = p.DefaultCoverageGroup OR p.DefaultCoverageGroup = 0)
    AND (cv.LevelOfCoverage = 1 OR cv.LevelOfCoverage IS NULL)
ORDER BY 
    p.AcctNumber, c.sDate

我尝试了MAX(COALESCE...MAX(CASE WHEN...的不同变体,但它们没有效果,或者他们不会显示空CoverageGroup的帐户。

知道我怎么能这样做吗?我在SQL方面的专业知识是初学者。

谢谢!

1 个答案:

答案 0 :(得分:0)

可能是因为:

AND (cv.Coveragegroup = p.DefaultCoverageGroup OR p.DefaultCoverageGroup = 0)

在这里,您实际上指定不允许NULL

您可以通过将其更改为以下内容来避免它:

AND (cv.Coveragegroup = p.DefaultCoverageGroup OR p.DefaultCoverageGroup = 0 OR cv.Coveragegroup IS NULL)