如何根据不同的条件从其他表中选择字段

时间:2021-02-05 23:34:11

标签: sql ms-access

我有一个 [Products] 表

let cbContainer = CallbackContainer()

var aVC: AViewController? = AViewController(container: cbContainer)
aVC?.viewDidLoad()
print ("callAll 1")
cbContainer.callAll()
print ("set to nil")
aVC = nil
print ("callAll 2")
cbContainer.callAll()

还有一张表 [Stores],数量在 2 个不同的仓库中,第一个仓库是 1,第二个是 2。

表[Stores]有产品的ID

ProductID | Productname 

1         | Bike
2         | Car

我想查询以显示每个产品的一条记录,如下

ProductID、ProductName、QtyFromFirstWhareHouse、QtyFromSecondWhareHouse

我试图对每个数量进行第二次查询,但我不知道要给出什么标准。 谢谢

你能帮我吗? 非常感谢

1 个答案:

答案 0 :(得分:0)

相关子查询可能是最简单的解决方案:

select p.*,
       (select s.qty
        from stores as s
        where s.productid = p.productid and s.warehouse = 1
       ) as quantity_1,
       (select s.qty
        from stores as s
        where s.productid = p.productid and s.warehouse = 2
       ) as quantity_2
from products as p;

注意:这里假设每个仓库/产品组合在 stores 表中有一行。如果有多行,那么您需要某种类型的聚合,例如 sum(s.qty)