SQL Query Clarification

前端 未结 4 619
耶瑟儿~
耶瑟儿~ 2021-01-23 20:37

I have two tables doctor and billing. I wish to view the dname,doctorid and sum(fees) of doctors treating more than one patient.

doctor table columns are as follows:

相关标签:
4条回答
  • 2021-01-23 20:55

    You have to mentioned into your query about which join you want to use,you have to change your query like

    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;
    

    Check Join

    0 讨论(0)
  • 2021-01-23 20:58

    FROM billing b,doctor d ON b.doctorid=d.doctorid should be FROM billing b inner join doctor d ON b.doctorid=d.doctorid

    0 讨论(0)
  • 2021-01-23 20:58

    You're missing the INNER JOIN keyword, and you also need to GROUP BY all the non-aggregate columns you're using in the SELECT clause (GROUP BY d.dname, b.doctorid in this case).

    Also, it might be a typo, but you haven't got a space between 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; 
    

    Remember using comma separated table names in a FROM clause will perform a cartesian product, which will be a performance killer depending on your RDBM's optimizer. In case you'd like to use it, remember to put its join conditions in the WHERE clause (the ON clause is used along with the JOIN syntax):

    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; 
    
    0 讨论(0)
  • 2021-01-23 20:59

    Try this

    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; 
    
    0 讨论(0)
提交回复
热议问题