MIN和COUNT Oracle SQL查询

时间:2012-11-25 12:33:35

标签: sql oracle oracle-sqldeveloper

我试过这个问题:每个医生数量较少的国家的医院是什么。 (第1栏:国家名称;第2栏:医院名称。如果医院数量较多的医院,则必须出现在结果上)。但结果不是我所期望的,并且它有语法错误。

我有这些表格:

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

我试过这个:

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
;    

感谢。

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

试试这个:

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;