Excellent! Views can be actually very complex and include clauses such as GROUP BY
or HAVING
. For instance, with the two tables from the previous exercises ...
CREATE TABLE doctor (
id integer PRIMARY KEY,
full_name varchar(128),
type varchar(32),
city varchar(128),
rating decimal(2, 1),
price_per_visit decimal(5, 2)
);
CREATE TABLE visit (
id integer PRIMARY KEY,
doctor_id integer,
visit_date date,
patient_id integer,
FOREIGN KEY (doctor_id) REFERENCES doctor(id),
FOREIGN KEY (patient_id) REFERENCES patient(id)
);
... we can create a view which will show the number of visits each doctor made on each day, given that there were at least two visits:
CREATE VIEW doctor_stats AS
SELECT
v.visit_date AS day,
d.full_name AS doctor_name,
COUNT(v.id) AS visit_count
FROM doctor d
JOIN visit v
ON v.doctor_id = d.id
GROUP BY v.visit_date, d.id, d.full_name
HAVING COUNT(v.id) > 1;
As you can see, views can also use more advanced SQL concepts. We'll talk more about that in the next section.