Mahmoud
Mahmoud

Reputation: 757

how to combine 2 different table?

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

Upvotes: 1

Views: 247

Answers (2)

heferav
heferav

Reputation: 769

Try a UNION query:

SELECT * FROM Cash_Expenses
UNION
SELECT * FROM Cheque_Expenses;

Upvotes: 1

BenV
BenV

Reputation: 12452

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;

Upvotes: 3

Related Questions