我有以下表格是sql
诊断
DiagnosisID
DiagnosisDescription
会员
MemberID
FirstName
LastName
DiagnosisCategoryMap
DiagnosisCategoryID
DiagnosisID
MemberDiagnosis
MemberID
DiagnosisID
我需要做的是找到每个会员类别中存在最低诊断ID的诊断
这是我到目前为止的sql:
SELECT MD.MemberID AS MID,
MD.DiagnosisID AS DID,
DM.DiagnosisCategoryID AS CID
FROM
MemberDiagnosis MD
INNER JOIN DiagnosisCategoryMap DM ON MD.DiagnosisID = DM.DiagnosisID
这给了我这个结果集:
> MID DID CID
> 1 2 2
> 1 4 3
> 3 3 3
> 3 4 3
我需要的结果集应如下所示:
> MID DID CID
1 2 2
3 3 3
我的查询中缺少什么。
我曾尝试过一个小组,但是(当然)效果不好,因为我无法正确地为小组聚合。
我正在使用SQL SERVER,这就是我可以使用的所有
答案 0 :(得分:2)
使用MIN
聚合使用GROUP BY获取每个MemberID和DiagnosisCategoryID的最小诊断ID
SELECT MD.MemberID AS MID,
MIN(MD.DiagnosisID) AS DID,
DM.DiagnosisCategoryID AS CID
FROM
MemberDiagnosis MD
INNER JOIN DiagnosisCategoryMap DM ON MD.DiagnosisID = DM.DiagnosisID
GROUP BY
MD.MemberID,
DM.DiagnosisCategoryID
答案 1 :(得分:0)
将问题分解为更小的步骤。
首先,验证您是否可以使用以下内容获得每个成员的最低诊断ID:
toString(C[1,1:2])
# [1] "48.4459, 9.989"
toString(C[1,3:4])
# [1] "49.0275, 8.7539"
sort(c(toString(C[1,1:2]), toString(C[1,3:4])))
# [1] "48.4459, 9.989" "49.0275, 8.7539"
确认无效后,请加入DiagnosisCategoryMap表...
select MemberId as MID, min(DiagnosisId) as DID
from MemberDiagnosis
group by MemberId
答案 2 :(得分:0)
SELECT A.ID AS MID, MIN(C.DiagnosisID) AS DID, C.DiagnosisCategoryID AS CID
FROM
Member A INNER JOIN MemberDiagnosis B
ON A.MemberID=B.MemberID
INNER JOIN DiagnosisCategoryMap C
ON B.DiagnosisID=C.DiagnosisID
GROUP BY A.ID, C.DiagnosisCategoryID;