-4

问题:显示与他们相关联的医生数量最多的医院的 hospitalid、hname、htype。

patient

patientid
pname
address
amount
ptype

hospital桌子_

hospitalid
hname
htype

doctor

doctorid
dname
specialization
hospitalid
status

billing

billingid
patientid
doctorid
fees
billdate

到目前为止,这就是我所拥有的:

select * from hospital where hospitalid =
  (select hospitalid from doctor group by hospitalid having count ( doctorid ) =
      (select max ( doctoramt ) from
          (select count (doctorid) as doctoramt from doctor group by hospitalid) as tbltemp));
4

3 回答 3

1

试试这个但未经测试

select * from hospital where hospitalid =
 (select hospitalid from doctor group by hospitalid having count ( doctorid ) =
  (select max ( doctoramt ) from
      (select count (doctorid) as doctoramt from doctor group by hospitalid) as tbltemp)));
于 2013-05-16T05:17:10.397 回答
0

您不能AS tbltemp在 Oracle 中使用别名表。该AS关键字只能用于别名列,不能用于表。您可以删除AS关键字,或者在这种情况下,因为您不引用别名,所以删除整个AS tbltemp部分。这是一个 SQL Fiddle

看起来解析器最初试图解释AS 为别名 name,然后不知道tbltemp应该是什么意思。

无论如何,ZZa 的方法更好,但您也可以使用分析函数来避免多次击中表格:

select hospitalid, hname, htype from (
  select hospitalid, hname, htype, doc_count,
    rank() over (order by doc_count desc) as rn
  from (
    select h.hospitalid, h.hname, h.htype,
        count(d.doctorid) as doc_count
    from hospital h
    join doctor d on d.hospitalid = h.hospitalid
    group by h.hospitalid, h.hname, h.htype
  )
)
where rn = 1;

另一个SQL Fiddle 在这里。最内层select进行计数,下一层将分组结果按每家医院医生人数的降序排列,最外层将其限制在排名最高的位置。

无论哪种方式,如果打成平手——两家医院的医生人数相同——你会得到多排。如果这不是你想要的,你需要决定如何打破平局。

于 2013-05-16T07:03:49.823 回答
0

尝试这个:

SELECT h.hospitalid, h.hname, h.htype 
FROM hospital h, doctor d
WHERE h.hospitalid = d.hospitalid
GROUP BY h.hospitalid, h.hname, h.htype 
HAVING COUNT(*) = (SELECT MAX(a) from (SELECT COUNT(*) a from doctor group by hospitalid));
于 2013-05-16T05:32:56.273 回答