简体   繁体   English

MySql:如何从不同的表中获取SUM值?

[英]MySql: How to get SUM values from different tables?

For each order I want get total for products and total of payments to get a balance. 对于每个订单,我希望获得产品总数和付款总额以获取余额。

This is a reduced version of tables: 这是表的简化版本:

ORDERS
--------------------
|ord_id|customer_id|
--------------------
|     1|        XYZ|
|     .|          .|
|     .|          .|
|     .|          .|
--------------------

ORDER_DETAILS
-----------------------------------------
|det_id|ord_id|product_id|quantity|price|
-----------------------------------------
|     1|     1|    AAA001|       3|   30|
|     2|     1|    BBB002|       2|    5|
|     .|     .|         .|       .|    .|
|     .|     .|         .|       .|    .|
|     .|     .|         .|       .|    .|
-----------------------------------------

PAYMENTS
----------------------
|pay_id|ord_id|amount|
----------------------
|     1|     1|    10|
|     2|     1|    20|
|     3|     1|    10|
|     .|     .|     .|
|     .|     .|     .|
|     .|     .|     .|
----------------------

This query does NOT return the correct values for the payments, only get a correct value for payments when count of products is the same for count of payments: 此查询不会返回正确的付款值,仅当产品计数与付款数相同时才获得正确的付款值:

SELECT o.ord_id, SUM(quantity * price) AS total_order, SUM(amount) AS total_payments
FROM orders AS o 
INNER JOIN order_details AS d ON o.ord_id = d.ord_id
INNER JOIN payments AS p ON o.ord_id = p.ord_id
GROUP BY o.ord_id

This is the expected result: 这是预期的结果:

-----------------------------------
|ord_id|total_order|total_payments|
-----------------------------------
|     1|        100|            40|
|     .|          .|             .|
|     .|          .|             .|
|     .|          .|             .|
-----------------------------------

Thanks in advance. 提前致谢。

Do the two queries separately, and join the results. 分别执行两个查询,然后合并结果。 To me that makes much more sense logically: 对我来说,从逻辑上讲更有意义:

SELECT
    ot.ord_id, 
    ot.order_total,
    op.order_paid
FROM
    (
        SELECT
            ord_id,
            SUM(price * quantity) AS order_total
        FROM
            ORDER_DETAILS
        GROUP BY
            ord_id
    ) AS ot
    INNER JOIN (
        SELECT
            ord_id,
            SUM(amount) AS order_paid
        FROM
            PAYMENTS
        GROUP BY
            ord_id
    ) AS op ON (op.ord_id = ot.ord_id)
;

...

 ord_id | order_total | order_paid 
--------+-------------+------------
      1 |         100 |         40
(1 row)

Try grouping by det_id and a WITH ROLLUP clause also: 尝试按det_idWITH ROLLUP子句进行分组:

SELECT o.ord_id, SUM(quantity * price) AS total_order, SUM(amount) AS total_payments
FROM orders AS o 
INNER JOIN order_details AS d ON o.ord_id = d.ord_id
INNER JOIN payments AS p ON o.ord_id = p.ord_id
GROUP BY o.ord_id, o.det_id WITH ROLLUP

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM