EDIT: Both of the following solutions require PatientStatus.StartDate be unique to each patient.
The traditional way (compatible with SQL Server 2000):
SELECT p.pkPatientId, p.FirstName, p.Surname, ps.StatusCode, ps.StartDate, ps.EndDate FROM Patient p INNER JOIN PatientStatus ps ON p.pkPatientId = ps.fkPatientId AND ps.StartDate IN ( SELECT TOP 2 StartDate FROM PatientStatus WHERE fkPatientId = ps.fkPatientId ORDER BY StartDate /* DESC (to switch between first/last records) */ ) WHERE EXISTS ( SELECT 1 FROM PatientStatus WHERE fkPatientId = p.pkPatientId GROUP BY fkPatientId HAVING COUNT(*) >= 2 ) ORDER BY ps.fkPatientId, ps.StartDate
A more interesting alternative (you need to try how well it performs in comparison):
SELECT p.pkPatientId, p.FirstName, p.Surname, ps.StatusCode, ps.StartDate, ps.EndDate FROM Patient p INNER JOIN PatientStatus ps ON p.pkPatientId = ps.fkPatientId WHERE /* the "2" is the maximum number of rows returned */ 2 > ( SELECT COUNT(*) FROM Patient p_i INNER JOIN PatientStatus ps_i ON p_i.pkPatientId = ps_i.fkPatientId WHERE ps_i.fkPatientId = ps.fkPatientId AND ps_i.StartDate < ps.StartDate /* switch between "<" and ">" to get the first/last rows */ ) AND EXISTS ( SELECT 1 FROM PatientStatus WHERE fkPatientId = p.pkPatientId GROUP BY fkPatientId HAVING COUNT(*) >= 2 ) ORDER BY ps.fkPatientId, ps.StartDate
Note: for MySQL, the last query may be the only alternative - as long as LIMIT is not supported in subqueries.
EDIT: I added a condition that excludes patients with only one PatientStatus . (Thanks for the tip, Ryan !)
Tomalak
source share