问题:显示与他们相关的医生数量最多的医院的医院,医院,医院类型。
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));
答案 0 :(得分: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)));
答案 1 :(得分: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));
答案 2 :(得分:0)
你走了。见SQL FIDDLE
答案 3 :(得分:0)
您无法使用AS tbltemp
为Oracle中的表设置别名。 AS
关键字只能用于别名列,而不能用于表。您可以删除AS
关键字,或者在这种情况下,因为您没有引用别名,请删除整个AS tbltemp
部分。 Here's an SQL Fiddle
看起来解析器最初会尝试将AS
解释为别名,然后不知道tbltemp
应该是什么意思。
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 here。最里面的select
进行计数,下一个级别按照每个医院的医生数量的降序对分组结果进行排序,最外层将其限制为排名最高的。
无论哪种方式,如果有一个平局 - 两家医院拥有相同数量的医生 - 你会得到多排。如果这不是你想要的,你需要决定如何打破平局。