-1

I need help. how can I convert this MySQL query count into MsSQL query

SELECT patientmasters.ID,
patientmasters.HRN,
patientmasters.LastName,
patientmasters.FirstName,
patientmasters.MiddleName,
 count(casehistories.PatientID) as NumberOfRecords        
from patientmasters
left join casehistories
on (patientmasters.ID = casehistories.PatientID)
group by
    patientmasters.ID;
RJ Berin
  • 13
  • 7

2 Answers2

1

This answer could be useful. For MS SQL Server it should be:

SELECT patientmasters.ID,
patientmasters.HRN,
patientmasters.LastName,
patientmasters.FirstName,
patientmasters.MiddleName,
count(casehistories.PatientID) as NumberOfRecords        
from patientmasters
left join casehistories
on (patientmasters.ID = casehistories.PatientID)
group by
    patientmasters.ID,
    patientmasters.HRN,
    patientmasters.LastName,
    patientmasters.FirstName,
    patientmasters.MiddleName;
0

In either database, I would recommend a correlated subquery:

select pm.*,
       (select count(*)
        from casehistories ch
        where pm.ID = ch.PatientID
       ) as NumberOfRecords        
from patientmasters pm;

In particular, both databases will take advantage of an index on casehistories(PatientID). This should have better performance by avoiding the outer aggregation.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786