获得已开具发票的付款总额以及每位客户的欠款

时间:2015-06-23 11:11:21

标签: mysql

我尝试过很多我在这里找到的脚本,但没有一个我需要的。

我有3个表:clientsinvoicedpayments

我想:

  • 将日期范围内每个客户的所有发票汇总
  • 汇总在日期范围内的客户的所有付款,然后从发票中扣除付款以显示未付金额。

我需要添加日期范围并获得总数(如果不是零)。

到目前为止,我的查询是

select id,
   (select sum(Total) from invoiced  where invoiced.ClientId = clients.Id) AS Invoiced,
   (select sum(Amount) from payments  where payments.ClientId = clients.Id) AS Paid
FROM clients

1 个答案:

答案 0 :(得分:0)

问题是发票和付款之间不存在关系。 这使它有点“肮脏”#34; ;)

试试这个:

select p.id, sum(i.total), sum(p.amount), sum(i.total) - sum(p.amount) as outstanding
from 
(
select c.id, coalesce(pay.amount,0) as amount
from 
  (select ClientId, Sum(Amount) amount from payments group by ClientId) as pay 
  right join clients c on c.id = pay.ClientId
) p
left join
(
select c.id, inv.total
from 
  (select ClientId, Sum(Total) total from invoiced group by ClientId) as inv
  left join clients c on c.id = inv.ClientId
) i
on p.id = i.id
group by id
having sum(i.total) <> sum(p.amount)
;

更新了Sqlfiddle with results here