SQL查询 - 医生和医院

时间:2013-05-15 16:04:49

标签: sql

  1. 显示医生,dname,治疗过多名病人的医生收到的总费用?
  2. 显示与他们相关的医生数量最多的医院的医院,hname,htype。
  3. 表1 - 患者

    patientid
    pname
    address
    amount
    ptype
    

    表2 - 医院

    hospitalid
    hname
    htype
    

    表3 - 医生

    doctorid
    dname
    specialization
    hospitalid
    status
    

    表4 - 结算

    billingid
    patientid
    doctorid
    fees
    billdate
    

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

    选择     billing.doctorid,     总和(费用)为总费用,     doctor.dname 从     计费,医生 哪里      doctor.doctorid = billing.doctorid 通过...分组     billing.doctorid,     doctor.dname 有     min(billing.patientid)<> max(billing.patientid)

2 个答案:

答案 0 :(得分:1)

我会帮你解决第一个问题,我会留给你第二个问题。

  
      
  1. 显示医生,dname,治疗过多名病人的医生收到的总费用?
  2.   

让我们将这个问题分成几部分:

因此,您首先需要知道哪些医生治疗了多名患者。该信息位于表billing中。所以:

select doctorId, count(patientId) as patientCount
from (select distinct doctorId, patientId from billing) as a
group by doctorId
having count(patientId)>1;

此查询将仅返回具有多个患者的医生的ID。请注意,我正在使用子查询对医生患者元组进行重复数据删除。

现在让我们来解决这个问题的另一部分:每个医生的总费用。同样,该信息位于表billing

select doctorId, sum(fees) as totalFees
from billing
group by doctorId;

最后,让我们把它们放在一起,并在表doctor中包含医生的信息:

select
    d.doctorId, d.doctorName, a.totalFees
from
    doctor as d
    inner join (
        select doctorId, sum(fees) as totalFees
        from billing
        group by doctorId
    ) as a on d.doctorId = a.doctorId
    inner join (
        select doctorId, count(patientId) as patientCount
        from (select distinct doctorId, patientId from billing) as a
        group by doctorId
        having count(patientId)>1;
    ) as b on d.doctorId = b.doctorId;

希望这有帮助


你需要学习和(或)记住的事情:

  1. 您需要了解如何关联存储在不同表中的数据。研究如何使用INNER JOIN(以及LEFT JOINRIGHT JOIN
  2. 您需要了解GROUP BY如何运作,以及如何使用汇总函数(sum()count()等等。
  3. 您知道如何编写子查询。现在尝试不仅将它们用于where条件,还将其用作数据源(包括from语句中的数据源)
  4. 保留一份RDBMS参考手册的副本。另外一本关于SQL的好书可以帮助你(去书店或图书馆找一个你喜欢的书)。

答案 1 :(得分:0)

看起来你已经得到了答案,但自从我写完后......

Select  d.doctorID, 
        d.dName, 
        Sum(b.fees) [total fees received]
From    doctor d
Join    billing b
        On  d.doctorID = b.doctorID
Group   By  d.doctorID, 
            d.dName
Having  Count(Distinct patientID) > 1

With    CTE As
(
        Select  Rank() Over (Order By Count(d.doctorID) Desc) As priCount, 
                h.hospitalID, 
                h.hName, 
                h.hType, 
                Count(d.doctorID) As doctors
        From    hospital h
        Join    doctor d
                On  h.hospitalID = d.hospitalID
        Group   By  h.hospitalID,
                    h.hName,
                    h.hType
)
Select  hosptitalID,
        hName,
        hType
From    CTE
Where   priCount = 1