Question

Given :

InsuranceCompanies (cid, name, phone, address)

Doctors (did, name, specialty, address, phone, age, cid)

Patients (pid, name, address, phone, age, gender, cid)

Visits (vid, did, pid, date, description)

Where:

cid - Insurance Company code
did - doctor code
pid - patient code
vid - code of visit

And a TASK : Find doctors (did, name) with number of visits (during this year) less than average number of visits to all doctors during this year.

My attempt is:

SELECT  D.did, D. name
FROM    Doctor D,Visit V
WHERE   V.did = D.did   and   D.did = CV.did   and   CV.visits <
                (SELECT AVG ( CV.visits) 
                 FROM   (SELECT V1.did AS did,COUNT(V1.vid) AS visits
                         FROM   Visit V1
                         WHERE  V1.date LIKE '%2012' 
                         GROUP BY   V1.did) AS CV)
Was it helpful?

Solution

A BIG THANKS TO Bridge Who shared the most beautifull and user freindly SQL commands visualator ever!

Databse Exemple : http://sqlfiddle.com/#!2/e85c7/3

Solution using views:

CREATE VIEW  ThisYear AS 
    SELECT v.pid,v.vid,v.did
    FROM Visits v
     WHERE v.date LIKE '%2012';

CREATE VIEW DoctorsVisitCount AS
    SELECT v.did, COUNT(v.vid) as c
    FROM ThisYear v
    GROUP BY v.did;

SELECT DISTINCT d.did,d.dname,dvc.c
FROM Doctors d,DoctorsVisitCount dvc
WHERE dvc.c < (SELECT AVG(dvc.c)
               FROM DoctorsVisitCount dvc);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top