表格 - BASECASE(CaseNumber,PatientID)
CaseNumber------PatientID
S100---------------P201
S101---------------P201
S102---------------P200
S103---------------P199
S104---------------P201
第二桌
Table - CHECKUP(CheckupNumber, CaseNumber)
CheckupNumber------CaseNumber
C301-------------------S100
C302-------------------S100
C303-------------------S101
C304-------------------S102
C305-------------------S103
SQL代码
SELECT CaseNumber FROM BASECASE
& COUNT(CaseNumber)FROM CHECKUP, WHERE PatientID='P201'
如果CHECKUP中不存在CaseNumber,则COUNT(CaseNumber)[将为null]应返回值0.
预期结果。
CaseNumber-----No.Of Checkups
S100------------------2
S101------------------1
S104------------------0
如何解决这个问题?
答案 0 :(得分:1)
您需要使用left join
和group by
select B.caseNumber, ISNULL(count(C.checkupNumber) ,0)
from BaseTable B
left join Checkup C
on B.caseNumber = C.caseNumber
where B.patientId ='P201'
group by B.caseNumber
答案 1 :(得分:1)
加入Group BY
select BC.Casenumber,isnull(COUNT(BC.Casenumber),0) CNT from BaseCase BC
left
join CheckUp Ch
on BC.CasetNumber=Ch.CaseNumber
group by BC.Casenumber
答案 2 :(得分:0)
您需要使用左加入与分组
SELECT cn.cno,Count(cp.cno)as NoCheckup from casenumber cn LEFT JOIN checkup cp ON cn.cno = cp.cno WHERE cn.patientid ='P201' GROUP BY cn.cno