SQL嵌套查询作业

鉴于:

保险公司(cid,姓名,电话,地址)

医生(确实,姓名,专业,地址,电话,年龄,cid)

患者(pid,姓名,地址,电话,年龄,性别,cid)

访问(vid,did,pid,日期,描述)

哪里:

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

一个任务:找到医生(确实,姓名),访问次数(在今年)低于今年所有医生的平均访问次数.

我的尝试是:

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)

最佳答案 非常感谢桥梁谁分享了最美丽和用户友好的SQL命令visualator!

数据库例程:http://sqlfiddle.com/#!2/e85c7/3

解决方案使用视图

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);
点赞