How can I sum columns across multiple tables in MySQL?

前端 未结 4 789
無奈伤痛
無奈伤痛 2020-12-06 06:05

In MySQL I have two tables:

Table MC:
----------------
|TransNo | Qty |
|--------|-----|
|  xxx1  |  4  | 
|  xxx3  |  3  |

and

<         


        
4条回答
  •  温柔的废话
    2020-12-06 06:44

    If you wish to avoid using Union or Union ALL (probably for efficiency reasons), then the following works:

    SELECT (1.Qty+2.Qty) AS total_qty FROM (SELECT SUM(Qty) Qty FROM MC) 1,
    (SELECT SUM(Qty) Qty FROM Amex) 2; 
    

    Here's an example for if you wish to expand this out to include a Group By condition. Let's say we have a Cust_ID on both MC and Amex to identify the customer which made each order, and we want to know the sums for each customer. The code would then look like this:

    SELECT COALESCE(1.Cust_ID, 2.Cust_ID) Cust_ID, (1.Qty+2.Qty) AS total_qty 
    FROM (SELECT Cust_ID, SUM(Qty) Qty FROM MC GROUP BY Cust_ID) 1 
    FULL OUTER JOIN (SELECT Cust_ID, SUM(Qty) Qty FROM Amex GROUP BY Cust_ID) 2 ON 1.Cust_ID = 2.Cust_ID; 
    

    If a Customer table exists in the database, then this can be simplified to:

    SELECT c.Cust_ID, (1.Qty+2.Qty) AS total_qty FROM Customer c 
    LEFT JOIN (SELECT Cust_ID, SUM(Qty) Qty FROM MC GROUP BY Cust_ID) 1 ON 1.Cust_ID = c.Cust_ID
    LEFT JOIN (SELECT Cust_ID, SUM(Qty) Qty FROM Amex GROUP BY Cust_ID) 2 ON 2.Cust_ID = c.Cust_ID;
    

提交回复
热议问题