如何结合2个不同的表?

时间:2022-12-20 20:24:17

how to combine 2 different tables where they contain the same fields but different data, example Cash_Expenses

如何组合2个不同的表,它们包含相同的字段但数据不同,例如Cash_Expenses

{
exp_date
exp_cat_id
exp_amount
exp_remark
}

Cheque_Espenses

Cheque_Espenses

{
exp_date
exp_cat_id
exp_cheque_NO
exp_amount
exp_remark
}

exp_cat

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

现在我想要做的是,我想将这三个结合起来并将金额加到它各自的猫,当我使用这个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;

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

如果总和不正确,我会得到重复,任何建议我很乐意为任何人学习

2 个解决方案

#1


3  

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


1  

Try a UNION query:

尝试UNION查询:

SELECT * FROM Cash_Expenses
UNION
SELECT * FROM Cheque_Expenses;

#1


3  

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


1  

Try a UNION query:

尝试UNION查询:

SELECT * FROM Cash_Expenses
UNION
SELECT * FROM Cheque_Expenses;