SQL JOIN, GROUP BY on three tables to get totals

前端 未结 5 1072
攒了一身酷
攒了一身酷 2020-12-14 21:17

I\'ve inherited the following DB design. Tables are:

customers
---------
customerid  
customernumber

invoices
--------
invoiceid  
amount

invoicepayments
         


        
5条回答
  •  春和景丽
    2020-12-14 21:29

    I am not sure I got you but this might be what you are looking for:

    SELECT i.invoiceid, sum(case when i.amount is not null then i.amount else 0 end), sum(case when i.amount is not null then i.amount else 0 end) - sum(case when p.amount is not null then p.amount else 0 end) AS amountdue
    FROM invoices i
    LEFT JOIN invoicepayments ip ON i.invoiceid = ip.invoiceid
    LEFT JOIN payments p ON ip.paymentid = p.paymentid
    LEFT JOIN customers c ON p.customerid = c.customerid
    WHERE c.customernumber = '100'
    GROUP BY i.invoiceid
    

    This would get you the amounts sums in case there are multiple payment rows for each invoice

提交回复
热议问题