查找访问过与其保险公司相关的所有骨科医生(专科)的患者。
数据库:单击此处查看 SQL Fiddle 中的示例数据脚本。
CREATE VIEW Orthos AS
SELECT d.cid,d.did
FROM Doctors d
WHERE d.speciality='Orthopedist';
CREATE VIEW OrthosPerInc AS
SELECT o.cid, COUNT(o.did) as countd4i
FROM Orthos o
GROUP BY o.cid;
CREATE VIEW OrthoVisitsPerPat AS
SELECT v.pid,COUNT(o.did) as countv4d
FROM Orthos o,Visits v,Doctors d
WHERE o.did=v.did and d.did=o.did
GROUP BY v.pid,d.cid;
SELECT p.pname,p.pid,p.cid
FROM OrthoVisitsPerPat v, OrthosPerInc i,Patient p
WHERE i.countd4i = v.countv4d and p.pid=v.pid and p.cid=i.cid;
DROP VIEW IF EXISTS Orthos,OrthosPerInc,OrthoVisitsPerPat;
我怎样才能把它写在一个查询上?
试图:
到目前为止,这是我解决这个问题的尝试。
SELECT p.pid,p.pname,p.cid,COUNT(v.did)
FROM Visits v
JOIN Doctors d ON v.did=d.did
JOIN Patient p ON p.pid=v.pid
WHERE d.cid=p.cid and d.speciality="Orthopedist"
GROUP BY p.pid,p.cid;
INTERSECT
SELECT p.pid,d.cid,COUNT(d.did)
FROM Doctors d
JOIN Patient p ON p.cid=d.cid
WHERE d.speciality='Orthopedist'
GROUP BY d.cid;