views:

72

answers:

2

Hey all

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

+3  A: 

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;
BenV
the data in cash_expenses and cheque_expenses shouldn't overlap, so UNION ALL would be more efficient (although this is MS Access, so possibly doing the sum on a pocket calculator would be more efficient)
Yellowfog
@Yellowfog: Good catch. I've updated accordingly.
BenV
@YellowFog - this is a site for objectivity, not product bashing. Access is more than capable for small database projects not involving simultaneous users.
John
@BenV i wanted to ask you, what if i want to split each amount on its receptive table, example when the i run the query, the amount is split into two fields one for cheque and other for cash is it possilbe or not
Mahmoud
@John there is a distinction between sarcasm and product bashing
edosoft
@edosoft how would a reader not knowing much about databases realise the difference? Sarcasm is _very_ difficult to put in writing especially for readers in a different country, so when giving a serious answer it's dangerous to add a sarcastic comment
John
@John: I would think most people would question the seriousness of comparing a pocket calculator to a database. Personally I appreciate a little humor. But I do understand the concern.
BenV
@BenV from experience, using sarcasm to people who don't share your culture or language very often goes wrong. Even if you use smilies :)
John
+1  A: 

Try a UNION query:

SELECT * FROM Cash_Expenses
UNION
SELECT * FROM Cheque_Expenses;
heferav