获取相同列但不同关系的SUM

时间:2015-03-10 03:10:53

标签: mysql join sum relationship

我正在为宠物诊所(学习练习)工作这个数据库,我想要做的是获得相同列的SUM,但不同的关系。

这些是我的表格(仅列出查询中使用的属性):

  

客户( customer_id ,customer_name)

     

员工( employee_id ,first_name,last_name)

     

宠物( pet_id ,owner_id,pet_name)

     

completed_service( completed_services_id ,visit_id,service_id)

     

访问( visit_id ,customer_id,employee_id,pet_id,日期)

     

服务( service_id ,名称,费用)

这是我尝试过的查询,它到目前为止获取了我想要的所有数据,但没有正确获取SUMS,我似乎无法理解该怎么做(如果可能的话)。我尝试做的是为每次宠物访问获取service.cost的总和,以及为客户所有访问获取service.cost的总和,之后我将添加where子句在日期,以便它只显示当前日期的实例:

    SELECT 
    customer.customer_name, 
    pet.pet_name, 
    visit.date,
    CONCAT(employee.first_name, ' ', employee.last_name) AS 'Veterenarian',
    performed_service.service_id, 
    service.name AS 'Treatment', 
    service.cost AS 'Price', 
    SUM(service.cost) AS 'Pet Total', 
    SUM(service.cost) AS 'Customer Total'

    FROM visit

    INNER JOIN customer
    ON visit.customer_id=customer.customer_id

    INNER JOIN employee
    ON visit.employee_id=employee.employee_id

    INNER JOIN pet
    ON visit.pet_id=pet.pet_id

    INNER JOIN performed_service
    ON visit.visit_id=performed_service.visit_id

    INNER JOIN service
    ON performed_service.service_id=service.service_id

    GROUP BY performed_service.performed_service_id

任何帮助将不胜感激!

0 个答案:

没有答案