Reputation: 129
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.
Upvotes: 4
Views: 7792
Reputation: 26861
Try grouping by det_id
and a WITH ROLLUP
clause also:
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
Upvotes: 0
Reputation: 44256
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)
Upvotes: 7