SQL嵌套查询作业SQL小提琴

时间:2012-04-25 11:10:35

标签: mysql sql nested-query

找到最多成员(患者)的保险公司。

这是数据库和我第一次尝试接近:

http://sqlfiddle.com/#!3/4b2ed/27

SELECT  P.cid AS cid, COUNT ( P.pid ) AS CountP
FROM        Patient P
GROUP BY    P.cid

我如何获得最大计数?

4 个答案:

答案 0 :(得分:4)

只需按照下降的患者数量排序您的结果,并且只记录第一条记录。

SELECT  P.cid AS cid, COUNT( P.pid ) AS CountP
FROM        Patient P
GROUP BY    P.cid
ORDER BY    CountP DESC
LIMIT 1

如果多个保险公司可能拥有最大数量的成员并且您想要获取所有这些成员,则需要使用子查询:

SELECT  P.cid AS cid, COUNT( P.pid ) AS CountP
FROM        Patient P
GROUP BY    P.cid
HAVING      CountP = (
    SELECT   COUNT(pid) AS c
    FROM     Patient
    GROUP BY cid
    ORDER BY c DESC
    LIMIT 1
);

在您在评论中描述的奇怪情况中,无法使用LIMIT,您可以这样做:

SELECT  P.cid AS cid, COUNT( P.pid ) AS CountP
FROM        Patient P
GROUP BY    P.cid
HAVING      CountP = (SELECT MAX(d.c) FROM (
    SELECT   COUNT(pid) AS c
    FROM     Patient
    GROUP BY cid
) AS d);

答案 1 :(得分:0)

尝试以下方法:
    MAX(计数(P.pid))

答案 2 :(得分:0)

SELECT  P.cid, COUNT ( P.pid ) AS CountP
FROM    Patient P
GROUP BY    P.cid
compute max(count(p.pid))

答案 3 :(得分:0)

哇 - 很多限制。你走了:

SELECT MAX(CountP) FROM (
  SELECT P.cid, COUNT ( P.pid ) AS CountP
  FROM  Patient P
  GROUP BY  P.cid
) winner