表
patientid
pname
address
amount
ptype
hospitalid
hname
htype
doctorid
dname
specialization
hospitalid
status
billingid
patientid
doctorid
fees
billdate
到目前为止,这就是我所拥有的:
选择 billing.doctorid, 总和(费用)为总费用, doctor.dname 从 计费,医生 哪里 doctor.doctorid = billing.doctorid 通过...分组 billing.doctorid, doctor.dname 有 min(billing.patientid)<> max(billing.patientid)
答案 0 :(得分:1)
我会帮你解决第一个问题,我会留给你第二个问题。
- 显示医生,dname,治疗过多名病人的医生收到的总费用?
醇>
让我们将这个问题分成几部分:
因此,您首先需要知道哪些医生治疗了多名患者。该信息位于表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;
希望这有帮助
你需要学习和(或)记住的事情:
INNER JOIN
(以及LEFT JOIN
和RIGHT JOIN
)GROUP BY
如何运作,以及如何使用汇总函数(sum()
,count()
等等。where
条件,还将其用作数据源(包括from
语句中的数据源)答案 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