简体   繁体   中英

MS Access SQL left join giving all 0

I am trying to make a summary table of all the items I have. I have a raw data table with 10 users who respectively have different items. There are maximum 3 different items and I want to do a count to see how many items each individual has. The following is my code.

Select b.Country,b.UserID,Num_including_fruits, Apple,Orange
from

(((SELECT o.Country,o.UserID, IIF(ISNULL(Count(o.UserID)),0,Count(o.UserID))
 AS Num_including_fruits
 FROM [SEA2_View] as o
 GROUP BY o.UserID, o.Country
 ORDER BY Country)as b

 LEFT JOIN

 (SELECT o.Country,o.UserID,IIF(ISNULL(Count(o.UserID)),0,Count(o.UserID)
    AS Apple
  FROM [APAC2_View] as o
  WHERE o.fruit_status <>"fresh" AND o.HWType = "Apple"
  GROUP BY o.Country,o.UserID)as d

  ON (b.UserID = d.UserID))

  LEFT JOIN

   (SELECT o.Country,o.UserID,IIF(ISNULL(Count(o.UserID)),0,Count(o.UserID))
    AS Orange
    FROM [SEA2_View] as o
    WHERE o.fruit_status <>"fresh" AND o.HWType = "Orange"
    GROUP BY o.Country,o.UserID)as e
    ON (d.UserID = e.UserID))
   ;

The first join returns the correct result but the second join somehow returns all 0, which is incorrect. Therefore please help! and I would appreciate any advice for best practice when it comes to joins in SQL. Thanks lot!

Are you sure you don't have a table naming error?

You're first joining [SEA2_View] with [APAC2_View] . The second join is joining with [SEA2_View] with itself.

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