2015-06-05 198 views
3

我有兩個表StockOutward和產品outward..I必須獲取總和(數量),不是等於總結(數量)stockOutward ..如何比較兩個SQL查詢值

StockOutward

 
Id ProductId Qty Location Orderid 

1  7  2  2  38 
2  8  1  2  38 
3  7  1  2  38 

ProductOutward

 
Id ProductId Qty Location Orderid 

1  7  12  2  38 
2  8  1  2  38 

我需要從stockoutward輸出作爲產品編號7

我用下面的查詢

Select 
    sum(qty) as Qty,ProductId 
from 
    StockOutward 
where 
    Orderid='38' 
group by 
    ProductId 

Union 

Select 
    sum(qty) as Qty, 
    ProductId 
from 
    ProductOutward 
where 
    Orderid='38' 
group by 
    ProductId 

回答

2

你可以使用JOIN和過濾不平等:

SELECT 
    s.ProductId 
FROM (
    SELECT 
     ProductId, 
     SumQty = SUM(Qty) 
    FROM StockOutward 
    GROUP BY ProductId 
)s 
INNER JOIN (
    SELECT 
     ProductId, 
     SumQty = SUM(Qty) 
    FROM ProductOutward 
    GROUP BY ProductId 
)p 
    ON p.ProductId = s.ProductId 
    AND p.SumQty <> s.SumQty 
+0

謝謝,我會測試和說@ wewesthemenace – Priya

1
Select sum(qty) as Qty,ProductId from StockOutward where Orderid='38' group by ProductId 
except 
Select sum(qty) as Qty,ProductId from ProductOutward where Orderid='38' group by ProductId