0

我希望显示hospitalid,hosp name and hosp type与他们相关的医生数量最多的医院。

我有两张桌子:

医生:doctorid, hospitalid

医院:hospitalid, hname, htype

SELECT d.hospitalid,h.hname,h.htype 
FROM doctor d 
INNER JOIN hospital h ON d.hospitalid = h.hospitalid 
GROUP BY d.hospitalid,h.hname,h.htype 
HAVING MAX(count(d.doctorid));

我尝试了上面的代码,但我得到一个错误“组函数嵌套太深”。我应该如何修改d代码?

4

2 回答 2

3

这是学习 SQL 时的常见错误,having Max(col)认为“只保留最大的行”。它只是意味着having <some function on the column> 没有任何条件。例如,您可以说having count(d.doctorid) = 1让医院只有一名医生。

这样做的方法是对列进行排序,然后取第一行。但是,“取第一行”的语法因数据库而异。以下适用于许多 SQL 方言:

SELECT d.hospitalid,h.hname,h.htype
FROM doctor d INNER JOIN
     hospital h
     ON d.hospitalid = h.hospitalid 
GROUP BY d.hospitalid,h.hname,h.htype
order by count(d.doctorid) desc
limit 1;

在 SQL Server 和 Sybase 中,语法为:

SELECT top 1 d.hospitalid,h.hname,h.htype
FROM doctor d INNER JOIN
     hospital h
     ON d.hospitalid = h.hospitalid 
GROUP BY d.hospitalid,h.hname,h.htype
order by count(d.doctorid) desc;

在甲骨文中:

select t.*
from (SELECT d.hospitalid,h.hname,h.htype
      FROM doctor d INNER JOIN
           hospital h
           ON d.hospitalid = h.hospitalid 
     GROUP BY d.hospitalid,h.hname,h.htype
     order by count(d.doctorid) desc
    ) t
where rownum = 1;

编辑(基于评论):

要获得最大值的所有行,您可以执行与原始查询类似的操作。只是更复杂。您可以使用子查询计算最大数量并在having子句中进行比较:

SELECT d.hospitalid, h.hname, h.htype
FROM doctor d INNER JOIN
     hospital h
     ON d.hospitalid = h.hospitalid  join
GROUP BY d.hospitalid,h.hname,h.htype
having count(d.doctorid) = (select max(NumDoctors)
                            from (select hospitalid, count(*) as NumDoctors
                                  from hospitalId
                                  group by hospitalid
                                 )  hd
                           )

需要注意的是,其他数据库中有更简单的机制。

于 2013-07-16T14:07:09.630 回答
0

这就是我为 SQL Server 编写它的方式。具体细节可能因您使用的数据库后端而异。

SELECT TOP 1 a.hospitalid,a.hname,a.htype
FROM 
(SELECT d.hospitalid,h.hname,h.htype, count(d.doctorid) as doctorcount FROM doctor d INNER JOIN hospital h ON d.hospitalid = h.hospitalid 
 GROUP BY d.hospitalid,h.hname,h.htype) a
ORDER BY doctorcount DESC;
于 2013-07-16T14:09:29.930 回答