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

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

I have two tables:

Patient

  • pkPatientId
  • FirstName
  • Surname

PatientStatus

  • pk
8条回答
  •  独厮守ぢ
    2021-02-02 04:03

    Check if your server supports windowed functions:

    SELECT * 
    FROM Patient p
    LEFT JOIN PatientStatus ps ON p.pkPatientId = ps.fkPatientId
    QUALIFY ROW_NUMBER() OVER (PARTITION BY ps.fkPatientId ORDER BY ps.StartDate) < 3
    

    Another possibility, which should work with SQL Server 2005:

    SELECT * FROM Patient p
    LEFT JOIN ( 
        SELECT *, ROW_NUMBER(PARTITION BY fsPatientId ORDER by StartDate) rn
        FROM PatientStatus) ps
    ON p.pkPatientId = ps.fkPatientID 
    and ps.rn < 3
    

提交回复
热议问题