MySQL - 使用SUM组合两个表

时间:2014-02-11 16:36:22

标签: mysql sql group-by sum

我正在使用MySQL 5.1,我有两个表,项目和员工。员工(number_project)中有一个外键,它是项目的主键(code_project)。

--->确切地说:SQL Fiddle

我正在尝试使用此查询按部门获取项目的SUM:

SELECT emp.department_emp AS Department, SUM( pro.price ) AS total_department
FROM employee AS emp, projects AS pro
WHERE emp.number_project = pro.code_project
GROUP BY emp.department_emp

它返回:

DEPARTMENT  TOTAL_DEPARTMENTA
Accounting   2600
IT           4200

但它应该回归:

DEPARTMENT  TOTAL_DEPARTMENT
Accounting   1300
IT           4200

问题在于,当同一部门的员工在该项目中工作时,查询对同一项目进行多次汇总。

谢谢!

3 个答案:

答案 0 :(得分:0)

您可以使用“折叠”员工的子查询,从项目中任意选择一名员工的部门:

SELECT department,
       SUM(price) AS total_department
  FROM ( SELECT project.code_project AS project,
                project.price AS price,
                MIN(employee.department_emp) AS department
          FROM project
          JOIN employee
            ON project.code_project = employee.number_project
         GROUP
            BY project.code_project,
               project.price
       )
 GROUP
    BY department
;

(当然,如果一个项目有来自多个不同部门的员工,这会产生误导性结果,因为它会将项目的全部价格分配给其中一个部门。)

答案 1 :(得分:0)

使用子查询创建唯一(department, project)组合的列表:

select  e.department_emp
,       sum(p.price)
from    (
        select  distinct department_emp
        ,       number_project
        from    Employee
        ) e
join    Projects p
on      p.code_project = e.number_project
group by
        e.department_emp

Working example at SQL Fiddle.

您的数据库可能会使用一些认真的工作。员工与项目的关系应该是多对多关系,而不是多对一关系。而名为“number”的字段不应该在另一个表中称为“代码”。

答案 2 :(得分:0)

SELECT emp.department_emp AS Department,SUM(pro.price)AS total_department FROM(SELECT DISTINCT * 从员工AS emp,项目AS专业 WHERE emp.number_project = pro.code_project AS P GROUP BY emp.department_emp