w3resource
SQL exercises

SQL exercises on hospital Database: Find the names of all patients who had at least two appointment where the nurse who prepped the appointment was a registered nurse and the physiccian who has carried out primary care

SQL hospital Database: Exercise-38 with Solution

38. Write a query in SQL to Obtain the names of all patients who had at least two appointment where the nurse who prepped the appointment was a registered nurse and the physiccian who has carried out primary care.

Sample table: appointment


Sample table: patient


Sample table: nurse


Sample table: physician


Sample Solution:

SELECT pt.name AS "Patient",
       p.name AS "Primary Physician",
       n.name AS "Nurse"
FROM appointment a
JOIN patient pt ON a.patient=pt.ssn
JOIN nurse n ON a.prepnurse=n.employeeid
JOIN physician p ON pt.pcp=p.employeeid
WHERE a.patient IN
    (SELECT patient
     FROM appointment a
     GROUP BY a.patient
     HAVING count(*)>=2)
  AND n.registered='true'
ORDER BY pt.name;

Sample Output:

    Patient    | Primary Physician |      Nurse
---------------+-------------------+-----------------
 Dennis Doe    | Christopher Turk  | Laverne Roberts
 Grace Ritchie | Elliot Reid       | Carla Espinosa
 Grace Ritchie | Elliot Reid       | Carla Espinosa
 John Smith    | John Dorian       | Carla Espinosa
 John Smith    | John Dorian       | Laverne Roberts
(5 rows)

Practice Online


E R Diagram of Hospital Database:

E R Diagram: SQL Hospital Database.

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?



New Content: Composer: Dependency manager for PHP, R Programming