MySQL SUM function in multiple joins

前端 未结 2 914
逝去的感伤
逝去的感伤 2021-01-21 10:44

Hi so this is my case I have those tables

Customer {id,name}
Charges {id,amount,customer_id}
Taxes {id,amount,charge_id}

so I want to SUM amoun

相关标签:
2条回答
  • 2021-01-21 11:01

    This is a pain because of the multiple hierarchies. I would suggest:

    SELECT c.id, ch.charge_amount, ch.taxes_amount
    FROM Customer c LEFT JOIN
         (SELECT ch.customer_id, SUM(ch.amount) as charge_amount,
                 SUM(t.taxes_amount) as taxes_amount
          FROM Charges ch LEFT JOIN
               (SELECT t.charge_id, SUM(t.amounts) as taxes_amount
                FROM taxes t
                GROUP BY t.charge_id
               ) t
               ON t.charge_id = ch.id
          GROUP BY ch.customer_id
         ) ch
         ON ch.customer_id = c.id;
    

    You are not going to be able to fix this without subqueries of one form or another, if there are multiple charges for a customer or multiple taxes on a charge.

    0 讨论(0)
  • 2021-01-21 11:02

    You want to know if you can do this without subqueries. No, you can't.

    If a row in Charges has more than one corresponding row in Taxes, you can't simply join the tables without duplicating Charges rows. Then, as you have discovered, when you sum them up, you'll get multiple copies.

    You need a way to get a virtual table (a subquery) with one row for each Charge.

                        SELECT ch.customer_id,
                               ch.amount amount,
                               tx.tax tax
                          FROM Charges
                          LEFT JOIN (  
                                      SELECT SUM(amount) tax,
                                             charge_id 
                                        FROM Taxes
                                       GROUP BY charge_id
                              ) tx ON ch.id = tx.charge_id
    

    You can then join that subquery to your Customer table to summarize sales by customer.

    0 讨论(0)
提交回复
热议问题