我正在使用三张桌子。
我正在尝试在单个查询中获取结果,该查询将从AccountingLine表返回ALL ROWS,并从Budget和Actuals表中为每个AccountingLine的SUM计算。
使用下面的SQL,SUM不适用于预算或实际数据。如果我删除其中一个连接和一个SUM函数,那么它会为单个连接表正确计算。非常奇怪......有人在MySQL中的三个或更多表上运行多个SUM函数吗?
SELECT A.*, SUM(B.`amount`) AS BudgetAmount, SUM(ACT.`amount`) as ActualAmount
FROM accounting_line A
LEFT JOIN budget B ON B.accounting_line_id = A.accounting_line_id
LEFT JOIN actual ACT ON ACT.accounting_line_id = A.accounting_line_id
GROUP BY A.`accounting_line_id`
通过发布上述声明,我希望看到accounting_line字段,每个accounting_line的预算金额的SUM以及每个accounting_line的实际金额的SUM。
我到处搜索过,无法找到多个SUM函数的实例。非常感谢任何建议。
约什
表数据如下:
Table: AccountingLine
act_line_id department
----------------------------------
1 Sales
2 HumanResources
Table: Budget
budget_id actg_line_id amount
----------------------------------------------
1 1 3500.00
2 2 5000.00
3 2 15000.00
Table: Actual
actual_id actg_line_id amount
----------------------------------------------
1 1 1000.00
2 2 500.00
3 2 9000.00
答案 0 :(得分:4)
join
重复另一个表中的每个匹配行。因此,如果三个表中有3行并将它们连接在一起,那么最终会有9行。如果总和,第二和第三个表中的每个总和都是3倍。
一种解决方案是在子查询中求和,以便join
只找到一行:
SELECT A.*
, B.SumAmount as BudgetAmount
, ACT.SumAmount as ActualAmount
FROM accounting_line A
LEFT JOIN
(
select accounting_line_id
, sum(amount) as SumAmount
from budget
group by
accounting_line_id
) as B
ON B.accounting_line_id = A.accounting_line_id
LEFT JOIN
(
select accounting_line_id
, sum(amount) as SumAmount
from actual
group by
accounting_line_id
) as ACT
ON ACT.accounting_line_id = A.accounting_line_id
答案 1 :(得分:2)
尝试此修改过的,在subquery
SELECT a.*, b.totalBudget, c.totalActual
FROM AccountingLine a LEFT JOIN
(
SELECT actg_line_id, SUM(amount) totalBudget
FROM Budget
GROUP BY actg_line_id
) b on a.act_line_id = b.actg_line_id
LEFT JOIN
(
SELECT actg_line_id, SUM(amount) totalActual
FROM Actual
GROUP BY actg_line_id
) c on a.act_line_id = c.actg_line_id
答案 2 :(得分:0)
试试这个
Select A.* ,SUM(B.Amount) As BudgetAmount,SUM(Act.Amount) As ActualAmount
from AccountingLine A
INNER JOIN Budget B
ON B.budget_id = A.actg_line_id
INNER JOIN Actual Act
ON Act.actual_id = A.accounting_line_id
Grounp By A.accounting_line_id