假设我在公司表中有两家公司1和公司2。每个公司有两个项目(项目1-1和项目1-2属于公司1.项目2-1和项目2-2属于公司2)。同样,每个项目都有两项费用(共8项费用)。我想列出所有公司,项目总预算和这些公司的总支出。 SQL查询(对于mysql)是什么样的?
公司表有两个字段(idfirm和name)。项目表有四个字段(idproject,name,budget和firm_idfirm作为外键)。最后,Expense表有三个字段(idexpense,amount和project_idproject作为项目表的idproject字段的外键引用。)
首先我尝试了这个查询
select firm.name as Firm, sum(project.budget) as Project, sum(expense.amount) as Expense
from firm, project, expense
where firm.idfirm = project.firm_idfirm and project.idproject = expense.project_idproject
group by firm.name;
但其结果显示每家公司的费用总和是正确的,但每家公司的预算总和不是。似乎预算是重复的。有什么建议吗?
答案 0 :(得分:2)
您需要分两步完成聚合。有几种表达方式,这就是我如何表达它......
SELECT
firm.name as Firm, SUM(project.budget) as budget, SUM (expense.expense) AS expense
FROM
firm
LEFT JOIN
project
ON firm.idfirm = project.firm_idfirm
LEFT JOIN
(SELECT project_idproject, SUM(amount) AS expense FROM expense GROUP BY project_idproject) AS expense
ON project.idproject = expense.project_idproject
GROUP BY
firm.name;
答案 1 :(得分:0)
至于为什么 budget
总和是错误的,想象一下没有sum
或group by
的查询结果。每个相关的project.budget
记录都会重复expense
值,但sum
不会考虑该值。它只是盲目地添加它们,使总和膨胀。
答案 2 :(得分:0)
select name, pbudget, peamount
from firm
inner join
(select firm_idfirm, sum(budget) as pbudget, sum(eamount) as peamount
from project
inner join
(select id, sum(amount) as eamount
from expense
group by project_idproject) e
on e.project_idproject = project.id
group by firm_idfirm) p
on firm.id = p.firm_idfirm