我尝试过很多我在这里找到的脚本,但没有一个我需要的。
我有3个表:clients
,invoiced
和payments
。
我想:
我需要添加日期范围并获得总数(如果不是零)。
到目前为止,我的查询是
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
答案 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)
;