I think you have gotten a little confused. Is this what you are looking for? DECLARE @patient TABLE ( [PatientKey] CHAR(1) , [PatientName] VARCHAR(50) )DECLARE @Prescription TABLE ( [PatientKey] CHAR(1) , [DrugKey] CHAR(1) , [DrugName] VARCHAR(50) ) INSERT @patient ([PatientKey], [PatientName])VALUES ('A', 'Andrew'), ('B', 'Boris')INSERT @Prescription ([PatientKey], [DrugKey], [DrugName])VALUES ('A', 'M', 'Morphine'), ('A', 'P', 'Paracetamol')SELECT * FROM @patientSELECT * FROM @PrescriptionSELECT pat.[PatientKey] AS [PatientKey] , COUNT(pre.[DrugKey]) AS [DrugKey]FROM @patient As pat LEFT OUTER JOIN @Prescription as Pre ON Pre.[PatientKey] = pat.[PatientKey]GROUP BY pat.[PatientKey]
Some things to note:1) I use JOIN's (ansi syntax)2) I use aliases for the tables (pat and pre)3) because there is no match on patient to prescription for Boris -- you get back a null. A Count on NULLS gives you a 0so the result are:PatientKey DrugKey---------- -----------A 2B 0
Charlie===============================================================Msg 3903, Level 16, State 1, Line 1736The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION