简体   繁体   中英

Inner Join SQL on Access

I cannot seem to get this and finally decided to ask for help. So we need to find the list of customer IDs from people who shopped at least 10 times from Store 25 and Store 50.

First I created the code to create a table that has the list of customer IDs and the count of the number of times they shopped at that store. The original transaction data has multiple lines for each transaction (for every item bought), hence the distinctTransactions table.

Then I tried to inner join the two shop tables on CustomerID and put in the > 9 criteria.

I get the error "The specified field 'CustomerID' could refer to more than one table listed in the FROM clause of your SQL statement." To me, that doesn't make sense because I joined the two tables under CustomerID.

If anyone can explain where this went wrong and the logic behind a correct response, I would be grateful! Also if this code is close, would I need two separate distinctTransactions tables (notice the second one I made distinctTransactionsc just to have it under a different name)?

SELECT CustomerID, Store25.ShopCount AS 25, Store50.ShopCount AS 50
FROM (SELECT CustomerID, COUNT(distinctTransactions.TransactionID) AS ShopCount
     FROM (SELECT DISTINCT TransactionID, CustomerID, StoreID 
         FROM TransactionT) AS distinctTransactions
         WHERE StoreID = 25
         GROUP BY CustomerID) AS Store25
INNER JOIN
    (SELECT CustomerID, COUNT(distinctTransactionsc.TransactionID) AS ShopCount
    FROM (SELECT DISTINCT TransactionID, CustomerID, StoreID 
        FROM TransactionT) AS distinctTransactionsc
        WHERE StoreID = 50
        GROUP BY CustomerID) AS Store50
    ON Store25.CustomerID = Store50.CustomerID
WHERE Store25.ShopCount > 9
AND Store50.ShopCount > 9
ORDER BY CustomerID

Even if you join tables on a common column name, you will have to precise from wich table CustomerID has to be selected in your ORDER BY and in your SELECT .

You can write store25.CustomerID or store50.CustomerID , there is no difference in your query with an inner join .

well the whole stuff sounds a bit wrong to me, you know? Why won't you simply use Group By count, customerId and store, then you could actually add "HAVING" with that criteria that you mentioned, that is Having count(*) > 9.

Or I didn't catch up something.

Best regards

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