2017-09-05 92 views
0

我有兩個疑問:比較來自不同表格的兩列的SUM()?

-- Getting the total no. of items CLAIMED for a sales order 
SELECT SUM(qty_claimed) As 'total_items_claimed' 
FROM so_claim_item 
WHERE sales_order_id = 1; 

-- Getting the total no. of items originally ORDERED for a sales order 
SELECT SUM(quantity) As 'total_items_ordered' 
FROM sales_order_item 
WHERE sales_order_id = 1; 

-- If the sums of the two columns are equal, return 1 or true. 
-- Else, return 0 or false. 

我需要比較不同表這兩列的總和,看是否銷售訂單是否完成。

如果返回1,意味着沒有。的項目聲稱等於沒有。訂購的物品,這意味着銷售訂單已完成。 否則,銷售訂單將保持無人認領/部分聲明。

這是迄今爲止我能想到的最好的解決方案,但我希望將它寫入一個查詢,只會返回一個值,如果可能的話。但是,如果你有更好的建議,我全都耳熟能詳。

回答

1

只需使用CASE

SELECT CASE 
     WHEN 
     (
      SELECT SUM(qty_claimed) AS 'total_items_claimed' 
      FROM so_claim_item 
      WHERE sales_order_id = 1 
     ) = 
     (
      SELECT SUM(quantity) AS 'total_items_ordered' 
      FROM sales_order_item 
      WHERE sales_order_id = 1 
     ) THEN 
      1 
     ELSE 
      0 
    END; 
0

嘗試使用具有如下:

SELECT SUM(qty_claimed) As 'total_items_claimed' 
    FROM so_claim_item A 
    WHERE A.sales_order_id = 1  
    having SUM(qty_claimed) =(SELECT SUM(quantity) As 'total_items_ordered') 
        FROM sales_order_item B 
        WHERE B.sales_order_id = 1) 

這裏有更多的信息關於having

0

我建議通過將值FROM子句中這樣做:

SELECT (sci.total_items_claimed = soi.total_items_ordered) as is_same 
FROM (SELECT SUM(qty_claimed) As total_items_claimed 
     FROM so_claim_item 
     WHERE sales_order_id = 1 
    ) sci CROSS JOIN 
    (SELECT SUM(quantity) As total_items_ordered 
     FROM sales_order_item 
     WHERE sales_order_id = 1 
    ) soi; 

您可以用子查詢中SELECT也這樣做:

SELECT ((SELECT SUM(qty_claimed) As total_items_claimed 
      FROM so_claim_item 
      WHERE sales_order_id = 1 
     ) = 
     (SELECT SUM(quantity) As total_items_ordered 
      FROM sales_order_item 
      WHERE sales_order_id = 1 
     ) 
     ) as is_same; 
相關問題