SQL加入澄清

时间:2013-07-16 14:02:13

标签: sql oracle

我希望显示医院的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));

我尝试了上面的代码,但是我得到一个错误“group func嵌套得太深了”。我该如何修改代码?

2 个答案:

答案 0 :(得分: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;

在Oracle中:

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
                           )

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

答案 1 :(得分: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;