-7
  1. 显示治疗过一名以上患者的医生收到的医生ID、名称、总费用?
  2. 显示与他们关联的医生数量最多的医院的 hospitalid、hname、htype。

表 1 - 患者

patientid
pname
address
amount
ptype

表 2 - 医院

hospitalid
hname
htype

表 3 - 医生

doctorid
dname
specialization
hospitalid
status

表 4 - 计费

billingid
patientid
doctorid
fees
billdate

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

选择 billing.doctorid, sum (fees) as totalfees, doctor.dname from billing, doctor where doctor.doctorid = billing.doctorid group by billing.doctorid, doctor.dname 有 min ( billing.patientid ) <> max ( billing.patientid )

4

2 回答 2

1

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

  1. 显示治疗过一名以上患者的医生收到的医生ID、名称、总费用?

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

因此,您首先需要知道哪些医生治疗过不止一名患者。该信息在表中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(and also LEFT JOINand RIGHT JOIN)
  2. 您需要了解它是如何GROUP BY工作的,以及如何使用聚合函数(sum()、、count()等等)。
  3. 您知道如何编写子查询。现在尝试不仅将它们用于where条件,而且将它们用作数据源(包括它们在from语句中)
  4. 手头保留一份 RDBMS 参考手册的副本。一本关于 SQL 的好书也可以帮助你(去书店或图书馆找到你喜欢的书)。
于 2013-05-15T16:38:51.710 回答
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
于 2013-05-15T17:02:34.060 回答