简体   繁体   中英

MS Access SQL - distinct records and count of related values

I'm running into a problem with an aggregate query. I've got two tables, MainA and MainC. I want to select only unique values in MainA and then count the number of matches to those values from MainC. I don't care (for now) about values that show up in MainC that aren't in MainA. I've got a simple expression mostly working, which is here:

SELECT DISTINCT TBMainA.Field1, Count(TBMainC.MCField1) AS CountOfMCField1
FROM TBMainA 
LEFT JOIN TBMainC ON TBMainA.Field1 = TBMainC.MCField1
GROUP BY TBMainA.Field1;

However, the problem is that if more than value shows up in MainA, the expression is double-counting the values in MainC (presumptively because there are two cases in MainA to count from). I suspect this has to do with where I'm starting the aggregation or how I'm grouping, but I've banged my head on this one for a bit and haven't produced a working solution yet. Here's some sample data along with the query output as it stands now (MAID and MCID are keys for each table):

MainA

MAID Field1
1 apples
2 oranges
3 grapefuit
4 peppers
5 kiwi fruit
6 tomatoes
8 avocado
9 bananas
10 apples

MainC

MCID MCField1
1 bananas
2 peppers
3 peppers
4 tomatoes
5 apples
6 spinach
7 kale
8 apples
9 oranges

Query output:

Field1 CountOfMCField1
apples 4
avocado 0
bananas 1
grapefuit 0
kiwi fruit 0
oranges 1
peppers 2
tomatoes 1

Suggestions welcomed, and thanks for your help...!

For your particular query, this would look like:

SELECT TBMainA.Field1, COUNT(TBMainC.MCField1) AS CountOfMCField1
FROM (SELECT DISTINCT TBMainA.Field1, TBMainC.MCField1
      FROM TBMainA LEFT JOIN
           TBMainC
           ON TBMainA.Field1 = TBMainC.MCField1
     ) as AC
GROUP BY TBMainA.Field1;

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