SELECT
Mem.MemberID, Mem.LastName + ', ' + Mem.FirstName AS Name,
MD.DiagnosisID,
Diag.DiagnosisDescription,
DC.DiagnosisCategoryID, DC.CategoryDescription, DC.CategoryScore
FROM
Member AS Mem
LEFT OUTER JOIN
MemberDiagnosis AS MD ON Mem.MemberID = MD.MemberID
LEFT OUTER JOIN
Diagnosis AS Diag ON MD.DiagnosisID = Diag.DiagnosisID
LEFT OUTER JOIN
DiagnosisCategoryMap AS Map ON Map.DiagnosisID = Diag.DiagnosisID
LEFT OUTER JOIN
DiagnosisCategory AS DC ON DC.DiagnosisCategoryID = Map.DiagnosisCategoryID
ORDER BY
Name ASC
我有这个查询,它会返回以下结果:
ID | Name | D.ID | D.Desc | C.ID | C. Desc | C.Score
----+---------------+------+----------------+------+-------------+----------
2 | Smith, Jack | NULL | NULL | NULL | NULL | NULL
1 | Smith, John | 2 | Test Diagnosis | 2 | Category B | 20
1 | Smith, John | 4 | Test Diagnosis | 3 | Category C | 30
3 | Smyth, Will | 3 | Test Diagnosis | 3 | Category C | 30
3 | Smyth, Will | 4 | Test Diagnosis | 3 | Category C | 30
在该查询和结果集中,如何使用;
为每人返回1行答案 0 :(得分:1)
尝试以下查询:
SELECT T1.*,Diag2.DiagnosisDescription, DC2.CategoryDescription, DC2.CategoryScore
FROM (SELECT DISTINCT
Mem.MemberID, Mem.LastName + ', ' + Mem.FirstName AS Name,
MIN(MD.DiagnosisID) OVER(PARTITION BY Mem.MemberID) AS DiagnosisID,
MIN(ISNULL(DC.DiagnosisCategoryID,1)) OVER(PARTITION BY Mem.MemberID) AS DiagnosisCategoryID
FROM
Member AS Mem
LEFT OUTER JOIN
MemberDiagnosis AS MD ON Mem.MemberID = MD.MemberID
LEFT OUTER JOIN
Diagnosis AS Diag ON MD.DiagnosisID = Diag.DiagnosisID
LEFT OUTER JOIN
DiagnosisCategoryMap AS Map ON Map.DiagnosisID = Diag.DiagnosisID
LEFT OUTER JOIN
DiagnosisCategory AS DC ON ISNULL(DC.DiagnosisCategoryID,1) = ISNULL(Map.DiagnosisCategoryID,1) ) AS T1
LEFT JOIN Diagnosis AS Diag2 ON T1.DiagnosisID = Diag2.DiagnosisID
LEFT JOIN DiagnosisCategory AS DC2 ON T1.DiagnosisCategoryID = DC2.DiagnosisCategoryID
ORDER BY T1.NAME