w3resource

SQL Exercise: Patients with at least one physician appointment

SQL hospital Database: Exercise-4 with Solution

4. From the following table, write a SQL query to count the number of patients who scheduled an appointment with at least one physician. Return count as "Number of patients taken at least one appointment".

Sample table: appointment


Sample Solution:


-- This SQL query counts the number of distinct patients who have taken at least one appointment from the appointment table.

SELECT count(DISTINCT patient) AS "No. of patients taken at least one appointment" -- Counts the number of distinct patients who have taken at least one appointment and aliases the result column
FROM appointment; -- Specifies the table from which to retrieve data, in this case, the appointment table

Sample Output:

 No. of patients taken at least one appointment
------------------------------------------------
                                              4
(1 row)

Explanation:

The given query in SQL that selects the number of distinct patients who have taken at least one appointment from a table 'appointment'.

The uses of COUNT and DISTINCT functions in combination with the patient column counts the number of unique patients in the table.

The query will return only a single row with a single column.

The AS keyword is used to provide a column alias, which renames the column to "No. of patients taken at least one appointment" for easier readability .

Pictorial presentation:

Count the number of patients who booked an appointment with at least one physician

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.

Previous SQL Exercise: Physicians who is the head of each department.
Next SQL Exercise: Find the floor and block with a given room number.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.