【发布时间】:2016-01-05 14:16:37
【问题描述】:
我需要我买的商品和我卖的商品之间的区别,我在这张桌子上买的商品
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
我试过了
第一季度:
SELECT ItemName, SUM(bought) as SumBought
FROM tBought GROUP BY ItemName
第二季度:
SELECT ItemName, SUM(sold) as SumSold
FROM tSold GROUP BY ItemName
第三季度:
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如果我没有卖掉这件商品的任何东西
因为这个例子是“水”
【问题讨论】:
-
我不明白 id 列。如果它没有意义,请摆脱它。此外,我会将其作为单个事务表来执行。
-
ok,不管ID列,我怎样才能得到我想要的结果
-
你快到了。查看OUTER JOINS。目前,您的 INNER JOIN 仅返回在已售表中包含 1 个或多个条目的购买项目。
标签: mysql sql-server ms-access