MS Access查询中的SQL查找

时间:2014-07-29 11:37:30

标签: sql ms-access lookup

我有一个包含表[Inventory]的Access数据库,其中包含以下字段:

[Inventory].[Warehouse]
[Inventory].[PartNumber]

我还有一个查询[TransactionsQry],其中包含以下fielfd:

[TransactionsQry].[PartNumber]
[TransactionsQry].[SumofTransactions]

现在,我想创建一个新查询,显示每个仓库的所有部件号(来自表[库存]),并查询查询[TransactionsQry]中的相关(数量)交易。并非[库存]中的每个零件编号都有交易,如果是,我想显示" 0"。

起初我使用DLookup成功尝试了这个,但结果是对非常少的数据进行非常慢的查询。

这就是我尝试以下操作的原因(但是仅显示匹配的部件号和其他错误信息失败):

SELECT 
    Inventory.Warehouse AS Warehouse, 
    TransactionsQry.PartNumber AS PartNumber, 
    TransactionsQry.SumofTransactions AS SumofTransactions
FROM Inventory 
    INNER JOIN TransactionsQry ON Inventory.PartNumber = TransactionsQry.PartNumber;

高度赞赏在SQL中解决此问题的任何帮助。感谢。

2 个答案:

答案 0 :(得分:0)

您希望使用left join而不是inner join。此外,表别名使查询更易于读写:

SELECT i.Warehouse AS Warehouse, 
       tq.PartNumber AS PartNumber, 
       nz(tq.SumofTransactions, 0) AS SumofTransactions
FROM Inventory as i LEFT JOIN
     TransactionsQry as tq
     ON i.PartNumber = tq.PartNumber;

但是,我猜你真的想要group by

SELECT i.Warehouse AS Warehouse, 
       tq.PartNumber AS PartNumber, 
       nz(sum(tq.SumofTransactions), 0) AS SumofTransactions
FROM Inventory as i LEFT JOIN
     TransactionsQry as tq
     ON i.PartNumber = tq.PartNumber
GROUP BY i.Warehouse, tq.PartNumber;

答案 1 :(得分:0)

根据您的需要,您将需要LEFT JOIN。与Nz一起将Nulls视为0.这是更正后的CODE

SELECT 
    Inventory.Warehouse AS Warehouse, 
    TransactionsQry.PartNumber AS PartNumber, 
    Nz(TransactionsQry.SumofTransactions, 0) AS SumofTransactions 
FROM 
    Inventory LEFT JOIN TransactionsQry 
ON 
    Inventory.PartNumber = TransactionsQry.PartNumber;