需要两列之间的差异,如果第二列有空项,则显示第一列中的数字

时间:2016-01-05 14:16:37

标签: mysql sql-server ms-access

我需要购买的商品和我销售的商品,我在此表中购买的商品之间的区别

  ID   |ItemName| PriceOfUnit  | NumberOfItems I bought |DateIBought| 
  1    |  tea   |       3      |            6           |15/11/2015 |
  2    | coffee |       5      |            4           |16/11/2015 |
  3    |  tea   |       4      |            10          |20/12/2015 |
  4    | juice  |       5      |            15          | 1/1/2016  |
  5    | coffee |       3      |            5           | 15/3/2016 |
  6    | water  |       5      |            2           | 16/4/2016 |

我销售的商品在此表中

  ID   |ItemName| PriceOfUnit  | NumberOfItems I sold   |DateIBought| 
  1    | coffee |       5      |            6           |  1/1/2016 |
  2    |  tea   |       5      |            9           | 15/3/2016 |
  3    | coffee |       4      |            2           | 20/4/2016 |
  4    | juice  |       5      |            11          |  1/1/2016 |

我需要在MS Access中使用查询,SQL查询或联合查询来获得此结果:

  ID   |ItemName| NumberOfItems I have   |
  1    | coffee |            1           |
  2    |  tea   |            7           |
  3    | juice  |            4           |
  4    |  water |            2           |

NumberOfItems I have = NumberOfItems I bought - NumberOfItems I sold

我试过这个

q1:

SELECT ItemName, SUM(bought) as SumBought 
FROM tBought GROUP BY ItemName 

q2:

SELECT ItemName, SUM(sold) as SumSold 
FROM tSold GROUP BY ItemName

q3:

SELECT q1.ItemName, (SumBought - SumSold) as difference 
FROM q1 inner join q2 on q1.ItemName = q2.ItemName

我得到了这个结果

  ID   |ItemName| NumberOfItems I have   |
  1    | coffee |            1           |
  2    |  tea   |            7           |
  3    | juice  |            4           |

我现在需要的是...如果我没有出售此商品的任何东西,则显示NumberOfItems I bought 这个例子是"水"

2 个答案:

答案 0 :(得分:-1)

我认为您可以将您的上一个查询更改为,以获取Q1中的项目(已购买的项目),即使它们都没有被出售。

SELECT q1.ItemName
     , (q1.SumBought - ISNULL(q2.SumSold, 0)) as difference 
  from q1 
  LEFT 
 OUTER
  join q2 
    on q1.ItemName = q2.ItemName

希望这有帮助。

答案 1 :(得分:-1)

在您现有的方法之上,您只需更改第3个查询即可outer join instead of inner join

SELECT q1.ItemName, 
       (ISNULL(SumBought, 0) - ISNULL(SumSold, 0)) as difference 
FROM q1 LEFT JOIN q2 on q1.ItemName = q2.ItemName

只是将所有内容都放在一个事务中,并且更好地优化执行计划,我建议使用CTE

;WITH q1 AS (
  SELECT ItemName, SUM(bought) as SumBought 
  FROM tBought GROUP BY ItemName ),
q2 AS (
  SELECT ItemName, SUM(sold) as SumSold 
  FROM tSold GROUP BY ItemName)
SELECT q1.ItemName, 
       (ISNULL(SumBought, 0) - ISNULL(SumSold, 0)) as difference 
FROM q1 LEFT JOIN q2 on q1.ItemName = q2.ItemName