简体   繁体   English

SQL-在SUM查询中使用COUNT

[英]SQL - Using COUNT in a SUM query

OK so here is my Database 好,这是我的数据库

Patient(PatID, GName, FName, Suburb, PhNo InsurNo)  
Doctor(DocID, DocName, DocSpec, Cost)  
Appointment(AppID, AppTimeDate, PatID*, DocID*)  
Meds(MedID, MedName, Purpose, Admin, AppID*)  
Tests(TestID, TestName, TestResult, TestDate, PatID*)  
DocPat(PatID*, DocID*)  

I am being asked to show the doctors name with the total cost of all appointments greater than average. 我被要求出示医生姓名,所有约会的总费用要比平均费用高。

so far I have: 到目前为止,我有:

SELECT d.DocName, sum((NO_OF_APPS)*DocCost)    
from doctor d, (select count(AppID) as NO_OF_APPS  
                from appointment  
                group by DocID)  
group by DocName;

trying to use sum(count(appID)*DocCost) i know i am coming at this from the wrong angle can anyone shed some light? 尝试使用sum(count(appID)* DocCost)我知道我是从错误的角度出发的,有人可以给我一些启示吗?

Have made corrective adjustments: 进行了纠正性调整:

SELECT d.DocName, d.docCost*COUNT(ap.AppID) as totalCost  
from doctor d  
left join appointment ap on ap.DocID=d.DocID  
GROUP BY d.DocID  
ORDER BY d.DocName  
HAVING totalCost > AVG(totalCost);

receiving '00933. 收到'00933。 00000 - "SQL command not properly ended' on Oracle SQL developer V4 00000-“ SQL命令未正确结束”在Oracle SQL Developer V4上

Use join instead of subselects, it is much clearer and usually works faster. 使用联接而不是子选择,它更加清晰,并且通常运行更快。 To analyze aggregation results you can use HAVING clause. 要分析聚合结果,可以使用HAVING子句。 Here is an example: 这是一个例子:

SELECT d.DocName, d.Cost*COUNT(a.AppID) as totalCost
from doctor d
left join appointment a on a.DocID=d.DocID
GROUP BY d.DocName
HAVING d.Cost > average(d.Cost);
ORDER BY d.DocName

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM