我在MySql中有三个表
T1
budgetId fin_year
---------------------
1 17-18
T2
divisionId budgetId totalAmount
-----------------------------------
1 1 10000
2 1 10000
3 1 10000
4 1 0
5 1 100
T3
workId divisionId budgetId workDescription workAmount
--------------------------------------------------------------
1 1 1 sssdfs 500
2 1 1 fsfcdsdfgfd 200
现在我希望T2表的 totalAmount 的总和以及相同budgetId的 T3的总WorkAmount 的总和
答案 0 :(得分:0)
尝试以下查询。
select sum(totalAmount) as total , budgetId , sum(workAmount) as total_used from T2
Left Join T3 on T3.budgetId = T2.budgetId
Group By budgetId
希望此查询对您有所帮助,如果您收到任何错误,请告诉我。
答案 1 :(得分:0)
如果您只是进行联接和每列的总和,那么您可能会遇到的问题可能会夸大您的预算金额。如果您有多个工作ID(T3),那么T2将为每个ID求和。您最好通过预算ID对T2和T3表进行一次预先求和并加入其中。这可以防止笛卡尔结果问题。
select
T1.fin_Year,
T2Sum.BudgetID,
T2Sum.TotalByBudget,
coalesce( T3Sum.WorkAmtPerBudget, 0.0 ) as WorkPerBudget
from
T1
JOIN
( select
budgetID,
sum( totalAmount ) TotalByBudget
from
T2
group by
budgetID ) T2Sum
on T1.budgetID = T2Sum.budgetID
LEFT JOIN
( select
budgetID,
sum( workAmount ) WorkAmtPerBudget
from
T3
group by
budgetID ) T3Sum
on T2Sum.BudgetID = T3Sum.BudgetID