SQL 嵌套查询作业 SQL 小提琴



查找会员(患者)数量最多的保险公司。

这就是数据库,也是我第一次尝试接近:

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

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

如何获得最大计数?

只需按患者数量降序排列结果,仅取第一条记录。

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

尝试以下操作:
最大(计数(P.pid))

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

哇 - 很多约束。 给你:

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

相关内容

  • 没有找到相关文章