两个表的总和与左连接与MySQL中的第一个表相乘

时间:2017-09-18 17:45:04

标签: mysql

我有两个值为

的表
Table1
invoice  item      Amount
05       banana    100
05       Apple     100
02       Avacado   150       

这里我有另一个table2具有不同的值

Table2
ID           Paid
05           50
05           20
02           0      

所以我在这里我想获取总发票金额和table1并减去付款金额并显示查询

所以在这里我已经尝试了这个,但我的table2付费金额乘以table1发票计数

查询我写的

select t1. invoice, sum(t1.amount)-sum(t2.paid) as left_amt 
 from table1 as t1 
 left join table2 as t2 on t1.invoice=t2.id 
 group by t1.invoice

我想要这样的预期输出

invoice      left_amt
05           130
02           150   

3 个答案:

答案 0 :(得分:1)

在加入这两个表之前,您需要对这两个表进行单独的分组,如

select ID, INV - coalesce(PAID,0) amt_left from
(select invoice, sum(amount) INV from table1 group by invoice) tbl1
 left join
(select ID, sum(paid) PAID from table2 group by ID) tbl2
 on invoice=id

修改:将其与left join一起更改为coalesce()。即使没有付款记录,这也会有效。

答案 1 :(得分:1)

因为我已经写出来了,这是我的版本:

select t1. invoice, sum(t1.amount)-t2.paid as left_amt from table1 as t1 left join (select t2.id, sum(t2.Paid) as paid from table2 as t2 group by t2.id) as t2 on t1.invoice = t2.id group by t1.invoice

您可以使用SQLFiddle here上的代码。

答案 2 :(得分:0)

试试这个

SELECT t1.invoice, sum(t1.amount) as inv_amount, 
   inv_amount-t2sum.inv_paid as left_amt
FROM table1 as t1 
LEFT JOIN (
   SELECT id as invoice, sum(paid) as inv_paid
   FROM table2
   GROUP BY id
   ) as t2sum on t1.invoice=t2sum.invoice
group by t1.invoice;