简体   繁体   English

MIN和COUNT个Oracle SQL查询

[英]MIN and COUNT Oracle SQL Query

I have tried to this query: What are the hospitals for each country with the lower number of doctors. 我尝试过以下查询:每个国家的医生人数较少的医院是哪些。 (1st column: name of the country; 2nd column: name of the hospital. In case of there is more than hospital with the lower number of doctors it must appear on the result). (第一列:国家名称;第二列:医院名称。如果有多家医院,而医生人数较少,则必须在结果中显示)。 But the result isn't what I expected and it has a syntax error. 但是结果不是我所期望的,并且有语法错误。

I have these tables: 我有这些表:

CREATE TABLE Hospital (
    hid INT PRIMARY KEY,
    name VARCHAR(127) UNIQUE,
    country VARCHAR(127),
    area INT
);
CREATE TABLE Doctor (
    ic INT PRIMARY KEY,
    name VARCHAR(127),
    date_of_birth INT,
);
CREATE TABLE Work (
    hid INT,
    ic INT,
    since INT,
    FOREIGN KEY (hid) REFERENCES Hospital (hid),
    FOREIGN KEY (ic) REFERENCES Doctor (ic),
    PRIMARY KEY (hid,ic)
);

I tried with this: 我尝试了这个:

SELECT DISTINCT H.country, H.name, MIN(*) 
FROM Hospital H
WHERE H.hid IN (
               SELECT COUNT(*)
               FROM Work W, Doctor D
               WHERE W.hid = H.hid AND W.ic = D.ic
               GROUP BY H.country
               )
GROUP BY H.country
;    

Thanks. 谢谢。

SELECT country, name
FROM
    (
        SELECT  hid, country, name, MIN(doctorCount)
        FROM
            (
                SELECT  a.hid, a.country, a.name, COUNT(b.hid) doctorCount
                FROM    Hospital a
                        LEFT JOIN Work b
                            ON a.hid = b.hid
                GROUP BY    a.hid, a.country, a.name
            ) x
        GROUP BY hid, country, name
    ) y

Try this: 尝试这个:

WITH doctorCount AS
  (SELECT H.country country, H.hid hid, COUNT(*) dCount
   FROM Work W, Doctor D, Hospital H
   WHERE W.ic = D.ic
   AND   H.hid = W.hid
   GROUP BY H.country, H.hid),
   minCount AS
  (SELECT D.country, MIN (D.dCount) lowCount
   FROM doctorCount D
   GROUP BY D.country)
SELECT D.country, H.name
FROM doctorCount D, Hospital H, minCount M
WHERE D.hid = H.hid
AND   M.country = D.country
AND   D.dCount = M.lowCount;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM