我正在使用UNION这个查询,其中包含金额的两个字段合并为一个表,我想将它们分成2个字段,首先是现金,另一个是检查
SELECT exp_cat.cat_name, SUM(exp_cheque.exp_amount) AS Cheque
FROM exp_cat INNER JOIN exp_cheque ON exp_cat.ID = exp_cheque.exp_cat_id
GROUP BY exp_cat.cat_name;
UNION
SELECT exp_cat.cat_name, SUM(exp_cash.exp_amount) As Cash
FROM exp_cat INNER JOIN exp_cash ON exp_cat.ID = exp_cash.exp_cat_id
GROUP BY exp_cat.cat_name;
请使用此链接了解每个表格结构 how to combine 2 different table?
答案 0 :(得分:1)
Select cat_name, sum(cash), sum(cheque) from
(SELECT exp_cat.cat_name, SUM(exp_cheque.exp_amount) AS Cheque,null as cash
FROM exp_cat INNER JOIN exp_cheque ON exp_cat.ID = exp_cheque.exp_cat_id;
UNION
SELECT exp_cat.cat_name, SUM(exp_cash.exp_amount) As Cash, null as cheque
FROM exp_cat INNER JOIN exp_cash ON exp_cat.ID = exp_cash.exp_cat_id;)
group by cat_name
现在不在IDE的前面,因此我可能会遇到语法错误,但这是一般的想法。
答案 1 :(得分:1)
Select exp_cat.cat_name
, (Select Sum(c1.exp_amount)
From exp_cheque As c1
Inner Join exp_cat As c2
On c2.Id = c1.exp_cat_id
Where c2.cat_name = exp_cat.cat_name) As cheque
, (Select Sum(c1.exp_amount)
From exp_cash As c1
Inner Join exp_cat As c2
On c2.Id = c1.exp_cat_id
Where c2.cat_name = exp_cat.cat_name) As cash
From exp_cat
Where exp_cat.cat_name Is Not Null
Group By exp_cat.cat_name
如果exp_cat.cat_name
上有唯一约束,则可以取消Group By子句。
鉴于这是Access,从长远来看,创建两个存储的现金查询和按exp_cat.cat_name
分组的检查可能更有效。然后你可以这样写:
Select exp_cat.cat_name
, Sum( cheque.Total ) As chequeTotal
, Sum( cash.Total ) As cashTotal
, Sum( cheque.Total ) + Sum( cash.Total ) As ChequeAndCashTotal
From exp_cat
Left Join chequeBycat_name As cheque
On cheque.exp_cat.cat_name = exp_cat.cat_name
Left Join cashBycat_name As cash
On cash.exp_cat.cat_name = exp_cat.cat_name
Where exp_cat.cat_name Is Not Null
Group By exp_cat.cat_name
两个查询中的每一个看起来都像:
Select exp_cat.cat_name, Sum(exp_cheque.exp_amount) As Total
From exp_cat
Inner Join exp_cheque
On exp_cheque.exp_cat_id = exp_cat.Id
Where exp_cat.cat_name Is Not Null
Group By exp_cat.cat_name
答案 2 :(得分:0)
我不确定我理解你的意思但是如果你想把结果放在不同的列中,这可能有用:
SELECT exp_cat.cat_name, SUM(exp_cheque.exp_amount) AS Cheque, null as Cash
FROM exp_cat INNER JOIN exp_cheque ON exp_cat.ID = exp_cheque.exp_cat_id
GROUP BY exp_cat.cat_name;
UNION
SELECT exp_cat.cat_name, null as Checque, SUM(exp_cash.exp_amount) As Cash
FROM exp_cat INNER JOIN exp_cash ON exp_cat.ID = exp_cash.exp_cat_id
GROUP BY exp_cat.cat_name;
答案 3 :(得分:0)
如果您想要相同cat_name的同一行返回现金和支票的总计,请尝试以下操作:
SELECT cat_name, sum(Cheque), sum(Cash)
(SELECT exp_cat.cat_name, exp_cheque.exp_amount AS Cheque, 0 as cash,
FROM exp_cat INNER JOIN exp_cheque ON exp_cat.ID = exp_cheque.exp_cat_id
UNION ALL
SELECT exp_cat.cat_name, 0 as Cheque, exp_cash.exp_amount As Cash
FROM exp_cat INNER JOIN exp_cash ON exp_cat.ID = exp_cash.exp_cat_id) sq
GROUP BY cat_name;