SQL JOIN, GROUP BY on three tables to get totals

前端 未结 5 1017
攒了一身酷
攒了一身酷 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:22

    Thank you very much for the replies!

    Saggi Malachi, that query unfortunately sums the invoice amount in cases where there is more than one payment. Say there are two payments to a $39 invoice of $18 and $12. So rather than ending up with a result that looks like:

    1   39.00   9.00
    

    You'll end up with:

    1   78.00   48.00
    

    Charles Bretana, in the course of trimming my query down to the simplest possible query I (stupidly) omitted an additional table, customerinvoices, which provides a link between customers and invoices. This can be used to see invoices for which payments haven't made.

    After much struggling, I think that the following query returns what I need it to:

    SELECT DISTINCT i.invoiceid, i.amount, ISNULL(i.amount - p.amount, i.amount) AS amountdue
    FROM invoices i
    LEFT JOIN invoicepayments ip ON i.invoiceid = ip.invoiceid
    LEFT JOIN customerinvoices ci ON i.invoiceid = ci.invoiceid
    LEFT JOIN (
      SELECT invoiceid, SUM(p.amount) amount
      FROM invoicepayments ip 
      LEFT JOIN payments p ON ip.paymentid = p.paymentid
      GROUP BY ip.invoiceid
    ) p
    ON p.invoiceid = ip.invoiceid
    LEFT JOIN payments p2 ON ip.paymentid = p2.paymentid
    LEFT JOIN customers c ON ci.customerid = c.customerid
    WHERE c.customernumber='100'
    

    Would you guys concur?

提交回复
热议问题