SQL查询错误:“右括号丢失缺失”

时间:2013-05-16 05:09:05

标签: sql oracle

问题:显示与他们相关的医生数量最多的医院的医院,医院,医院类型。

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 个答案:

答案 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应该是什么意思。

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

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进行计数,下一个级别按照每个医院的医生数量的降序对分组结果进行排序,最外层将其限制为排名最高的。

无论哪种方式,如果有一个平局 - 两家医院拥有相同数量的医生 - 你会得到多排。如果这不是你想要的,你需要决定如何打破平局。