1

我有两张表医生和计费。我希望查看治疗一名以上患者的医生的 dname、医生 ID 和总和(费用)。

医生表列如下:

doctorid,dname

计费表列如下:

billid,patientid,doctorid,fees

我尝试了以下代码。但收到错误提示 SQL cmd 未正确结束:

SELECT d.dname,b.doctorid,Sum(b.fees)as "TotalFees" FROM billing b,doctor d ON b.doctorid=d.doctorid
GROUP BY b.doctorid HAVING count(b.patientid)>1; 

我的语法哪里出错了?谢谢...

4

4 回答 4

1

FROM billing b,doctor d ON b.doctorid=d.doctorid应该 FROM billing b inner join doctor d ON b.doctorid=d.doctorid

于 2013-07-16T13:22:32.180 回答
1

您缺少INNER JOIN关键字,还需要GROUP BYSELECT在子句中使用的所有非聚合列(GROUP BY d.dname, b.doctorid在本例中)。

Sum(b.fees)此外,这可能是一个错字,但你在and之间没有空格as

SELECT d.dname, b.doctorid, Sum(b.fees) as "TotalFees" 
FROM billing b INNER JOIN doctor d ON b.doctorid=d.doctorid
GROUP BY d.dname, b.doctorid HAVING count(b.patientid)>1; 

请记住,在子句中使用逗号分隔的表名将FROM执行笛卡尔积,这将成为性能杀手,具体取决于您的 RDBM 优化器。如果您想使用它,请记住将其连接条件放在WHERE子句中(该ON子句与JOIN语法一起使用):

SELECT d.dname, b.doctorid, Sum(b.fees) as "TotalFees" 
FROM billing b, doctor d 
WHERE b.doctorid = d.doctorid
GROUP BY d.dname, b.doctorid HAVING count(b.patientid)>1; 
于 2013-07-16T13:22:52.567 回答
1

您必须在查询中提到要使用哪个联接,您必须更改查询,例如

SELECT d.dname, b.doctorid, Sum(b.fees) as "TotalFees" 
FROM billing b inner join doctor d ON b.doctorid=d.doctorid
GROUP BY d.dname, b.doctorid HAVING count(b.patientid)>1;

检查加入

于 2013-07-16T13:24:13.913 回答
1

尝试这个

SELECT d.dname,b.doctorid,Sum(b.fees)as "TotalFees" FROM billing b inner join doctor d ON b.doctorid=d.doctorid
GROUP BY d.dname,b.doctorid HAVING count(b.patientid)>1; 
于 2013-07-16T13:25:52.953 回答