SQL - 在SUM查询中使用COUNT

时间:2014-05-20 12:50:48

标签: mysql sql sql-server database ms-access

好的,这是我的数据库

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*)  

我被要求出示医生姓名,所有预约的总费用高于平均水平。

到目前为止,我有:

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;

尝试使用sum(count(appID)* DocCost)我知道我从错误的角度来到这个可以让任何人摆脱一些光吗?

进行了纠正调整:

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);

收到'00933。 00000 - Oracle SQL开发人员V4上的“SQL命令未正确结束”

1 个答案:

答案 0 :(得分:2)

使用join而不是subselects,它更清晰,通常工作得更快。要分析聚合结果,您可以使用HAVING子句。这是一个例子:

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