如何比较两个SQL查询值

时间:2015-06-05 04:51:40

标签: sql-server sql-server-2008

我有两个表StockOutward和产品向外..我必须获取总和(数量)不等于总和(数量)stockOutward ..

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的输出作为ProductId 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 个答案:

答案 0 :(得分: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

答案 1 :(得分: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