在连接表上使用STUFF并用常量字符串替换NULL值

时间:2018-03-04 08:50:16

标签: sql sql-server

尝试使用以下代码获取联接表的结果。是否可以将查询结果与连接结合在一起,同时替换NULL值?我尝试了下面的代码,但我不能让他们使用GROUP BY。

SELECT
    tblAdmission.AdmissionID
    , CONCAT(LastName, ', ', FirstName) [Name]
    , Birthdate
    , AdmissionDate
    , Ward
    , Service
    , Outcome
    , ISNULL(
        STUFF((SELECT ',' + OrganismName
            FROM tblOrganism
            WHERE tblOrganism.OrganismID = tblHAIFile.OrganismID
            FOR XML PATH('')), 1, 1, '')
        , 'No Isolate Found') [Isolated Organisms]
FROM
    tblAdmission
INNER JOIN tblPatient ON tblAdmission.PatientID = tblPatient.PatientID
INNER JOIN tblHAIFile ON tblAdmission.AdmissionID = tblHAIFile.AdmissionID
LEFT JOIN tblOrganism ON tblHAIFile.OrganismID = tblOrganism.OrganismID

GROUP BY
    tblAdmission.AdmissionID, CONCAT(LastName, ', ', FirstName),
    Birthdate, AdmissionDate, Ward, Service, Outcome, tblHAIFile.OrganismID

这是上面查询的当前输出,以及我正在尝试创建的那个:https://imgur.com/yXCmtsZ

1 个答案:

答案 0 :(得分:1)

只需使用horizontal

COALESCE()

另外,我怀疑你在外部查询中需要SELECT . . . STUFF((SELECT ',' + COALESCE(o.OrganismName, 'No Isolate Found') FROM tblOrganism o WHERE o.OrganismID = tblHAIFile.OrganismID FOR XML PATH('') ), 1, 1, '' ) as [Isolated Organisms] 。 。 。你也可能不需要tblOrganism

GROUP BY

通常,您不希望表格收集外部SELECT . . ., STUFF((SELECT ',' + COALESCE(o.OrganismName, 'No Isolate Found') FROM tblOrganism o WHERE o.OrganismID = tblHAIFile.OrganismID FOR XML PATH('') ), 1, 1, '' ) as [Isolated Organisms] FROM tblAdmission a INNER JOIN tblPatient p ON a.PatientID = p.PatientID; 字符串中的项目。

此外,此方法基于XML。完全不需要FROMSTUFF()只删除第一个逗号 - 这是操作中一个非常不重​​要的部分。