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

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

I have two tables:

Patient

  • pkPatientId
  • FirstName
  • Surname

PatientStatus

  • pk
8条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-02 04:16

    Here is how I would approach this:

    -- Patients with at least 2 status records
    with PatientsWithEnoughRecords as (
        select fkPatientId
            from PatientStatus as ps
            group by 
                fkPatientId
            having
                count(*) >= 2
    )
    select top 2 *
        from PatientsWithEnoughRecords as er 
            left join PatientStatus as ps on
                er.fkPatientId = ps.fkPatientId
        order by StartDate asc
    

    I am not sure what determines the "first" two status records in your case, so I assumed you want the earliest two StartDate**s. Modify the last **order by clause to get the records that you are interested in.

    Edit: SQL Server 2000 doesn't support CTEs, so this solution will indeed only work directly on 2005 and later.

提交回复
热议问题