简体   繁体   中英

SQL Lookup in MS Access Query

I have an Access Database with a table [Inventory] with following fields:

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

I also have a query [TransactionsQry] with following fielfd:

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

Now I would like to make a new query which shows all part numbers per Warehouse (from table [Inventory]) and look up related (number of) transactions in query [TransactionsQry]. Not every part number in [Inventory] has transactions yet and if so I would like to display "0".

At first I successfully tried this with a DLookup, but the result is a very slow query for very little data.

That is why I tried the following (but unsuccessfully displaying only matched part numbers and an additional error message):

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

Any help with solving this issue in SQL is highly appreciated. Thanks.

You want to use left join rather than inner join for this. Also, table aliases make queries easier to read and write:

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;

However, I'm guessing that you really want a 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;

You would be needing a LEFT JOIN based on what you need. Along with a Nz to treat Nulls as 0. Here is the corrected 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM