2011-12-03 51 views
2

對於每個訂單,我想獲得產品總額和付款總額以獲得餘額。MySql:如何從不同的表中獲取SUM值?

這是表的簡化版本:

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| 
|  .|  .|  .| 
|  .|  .|  .| 
|  .|  .|  .| 
---------------------- 

此查詢不返回支付正確的價值觀,只得到付款正確的值時,產品計數付款的數量是相同的:

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 

這是預期的結果:

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

感謝我前進。

回答

6

分別做兩個查詢,並加入結果。對我來說,讓邏輯上更有意義:

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) 
0

嘗試通過det_id分組和WITH 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 
+0

我得到語法錯誤與修正(MySQL版本:5.1.41)。我檢查文檔(http://dev.mysql.com/doc/refman/5.0/en/group-by-modifiers.html),但我看到該條款正確。 – Leonardo

相關問題