I'm stuck with a query not returning unique records.

I have following tables:

```
clinics (id => PK)
patients (id => PK, clinic_id => FK)
patient_visits(id => PK, patient_id => FK, clinic_id => FK)

```

A patient is registered to a clinic. A patient can visit to any clinic any number of times.
What I want is to return all unique patients who visited in a clinic.

I tried following query which is not returning unique records for a clinic

```
SELECT v.id
     , v.patient_id
     , v.clinic_id
     , c.name clinic_name
     , p.name
     , p.mobile
     , p.email
     , p.gender
     , p.created_at
     , last_visit_date
     , visit_count 
  FROM 
     ( SELECT DISTINCT patient_id
                     , clinic_id 
                  FROM patient_visits
     ) pat
  JOIN patient_visits v
    ON pat.patient_id = v.patient_id 
  JOIN clinics c
    ON c.id = v.clinic_id 
  JOIN patients p
    ON p.id = v.clinic_id 
  JOIN 
     ( SELECT patient_id
            , MAX(patient_visits.created_at) last_visit_date
            , COUNT(patient_visits.created_at) visit_count 
         FROM patient_visits 
        GROUP 
           BY patient_id
     ) visits_aggregate 
    ON visits_aggregate.patient_id = p.id 
 WHERE v.clinic_id = ? 
 ORDER 
    BY visit_date

```

One problem I understand is if I join with patient\_visits, it will pick matching duplicate patient\_id, clinic\_id combination.