SQL嵌套查询作业

时间:2012-04-25 08:30:53

标签: sql nested-query

鉴于:

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

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

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

访问次数( vid ,确实,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)

1 个答案:

答案 0 :(得分:2)

非常感谢能够分享最美观,最友好的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);