如何合并2个包含相同字段但数据不同的不同表,例如Cash_Expenses
{ exp_date exp_cat_id exp_amount exp_remark }
支票
{ exp_date exp_cat_id exp_cheque_NO exp_amount exp_remark }
exp_cat
{ cat_id Cat_name }
现在我想做的是,我想将这三个结合起来,并将其总和加到各自的猫身上,当我使用此sql语句时
SELECT DISTINCT exp_cat.cat_name, Sum(exp_cash.exp_amount) AS SumOfexp_amount, Sum(exp_cheque.exp_amount) AS SumOfexp_amount1 FROM (exp_cat INNER JOIN exp_cheque ON exp_cat.ID = exp_cheque.exp_cat_id) LEFT JOIN exp_cash ON exp_cat.ID = exp_cash.exp_cat_id GROUP BY exp_cat.cat_name;
如果重复的金额不正确,我会得到重复,任何建议我都会很高兴为任何人学习
这应该使您接近:
select cat_name, sum(exp.exp_amount) from (select exp_cat_id, exp_amount from cash_expenses union all select exp_cat_id, exp_amount from cheque_expenses) as exp inner join exp_cat on exp.cat_id = exp_cat.cat_id group by cat_name;