SQL query - Join that returns the first two records of joining table

后端 未结 8 1741
陌清茗
陌清茗 2021-02-02 03:50

I have two tables:

Patient

  • pkPatientId
  • FirstName
  • Surname

PatientStatus

  • pk
8条回答
  •  后悔当初
    2021-02-02 04:09

    Adding this WHERE clause to the outer query of Tomalak's first solution will prevent Patients with less than 2 status records from being returned. You can also "and" it in the WHERE clause of the second query for the same results.

    WHERE pkPatientId IN (
        SELECT pkPatientID 
        FROM Patient JOIN PatientStatus ON pkPatientId = fkPatientId
        GROUP BY pkPatientID HAVING Count(*) >= 2
    )
    

提交回复
热议问题