how to combine 2 different table?

不打扰是莪最后的温柔 提交于 2019-12-24 15:41:18

问题


how to combine 2 different tables where they contain the same fields but different data, example 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
}

now what i am trying to do is that i want to combine those three and sum the amount to its respective cat, where when i use this sql statment

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;

i get duplications where the sum is incorrect, any suggestion i well be glad to learn for anyone


回答1:


This should get you close:

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;



回答2:


Try a UNION query:

SELECT * FROM Cash_Expenses
UNION
SELECT * FROM Cheque_Expenses;


来源:https://stackoverflow.com/questions/3260980/how-to-combine-2-different-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!