如何组合2个不同的表,它们包含相同的字段但数据不同,例如 Cash_Expenses
{
exp_date
exp_cat_id
exp_amount
exp_remark
}
Cheque_Espenses
{
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;
我得到的重复是总和不正确,任何建议我很乐意为任何人学习
答案 0 :(得分:3)
这应该让你接近:
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;
答案 1 :(得分:1)
尝试使用UNION查询:
SELECT * FROM Cash_Expenses
UNION
SELECT * FROM Cheque_Expenses;