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

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

I have two tables:

Patient

  • pkPatientId
  • FirstName
  • Surname

PatientStatus

  • pk
8条回答
  •  感动是毒
    2021-02-02 03:59

    Ugly, but this one does not rely on uniqueness of StartDate and works on SQL 2000

    select * 
    from Patient p 
    join PatientStatus ps on p.pkPatientId=ps.fkPatientId
    where pkPatientStatusId in (
     select top 2 pkPatientStatusId 
     from PatientStatus 
     where fkPatientId=ps.fkPatientId 
     order by StartDate
    ) and pkPatientId in (
     select fkPatientId
     from PatientStatus
     group by fkPatientId
     having count(*)>=2
    )
    

提交回复
热议问题