The SQL Distinct Key Word

This solution is for returning one record per user with either a min or max value in one of the record's fields.

---------------------------------------------------------------
SELECT DISTINCT ON (P.ID) PR.PRACTICENAME AS "Practice", P.FIRSTNAME AS "First Name", P.MIDDLENAME AS "Middle Name", P.LASTNAME AS "Last Name", A.DATE::date AS "Last Appointment Date"

FROM PEOPLE AS P
JOIN CLIENT C ON C.ID = P.CLIENT_ID
JOIN PRACTICE PR ON PR.ID = P.PRACTICE_ID
JOIN APPOINTMENT A ON A.CLIENT_ID = C.ID

WHERE A.DATE IS NOT NULL

ORDER BY P.ID, A.DATE DESC
--------------------------------------------------------------- 

The beauty of this query is that is returns only the record for each client's latest appointment without  the use of complex sub-queries. Granted, the results may have to be further sorted, either using SQL or another tool, but it does return only one row per CLIENT and that row is for their LATEST appointment date.
Post a Comment