这是学习 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
)
需要注意的是,其他数据库中有更简单的机制。