SQL Server中两个单独表中两列之间的差异

时间:2014-10-04 22:34:10

标签: sql sql-server difference

我在SQL Server中有两个表:

 Product_Brought (
     Product_ID, Quantity_Brought,  ....
 )

 Product_Distribution (
    Product_ID,  Quantity_Sold, ....
 )

我想通过计算它们的差异来计算这两个表中这两列的手头余额。我做过类似的事情,但它正在回归一些没有意义的事情。

SELECT 
   DIFFERENCE((SELECT sum(Quantity_Brought) 
FROM 
   Product_Brought), 
   (SELECT sum(Quantity_Sold) FROM Product_Distribution))

1 个答案:

答案 0 :(得分:2)

您可以在子查询中计算SUM,然后进行减法。

SELECT T1.TotalBrought - T2.TotalSold as BalanceOnHand
FROM
(SELECT SUM(Quantity_Brought) as TotalBrought
FROM Product_Brought
) T1,
(SELECT SUM(Quantity_Sold) as TotalSold
FROM Product_Distribution
) T2