简体   繁体   English

MS Access SQL - 不同的记录和相关值的计数

[英]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.我有两个表,MainA 和 MainC。 I want to select only unique values in MainA and then count the number of matches to those values from MainC.我只想在 MainA 中选择唯一值,然后计算 MainC 中与这些值匹配的次数。 I don't care (for now) about values that show up in MainC that aren't in MainA.我不关心(现在)在 MainC 中出现但不在 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).然而,问题是如果 MainA 中出现的值大于 value,则表达式会重复计算 MainC 中的值(推测是因为 MainA 中有两种情况要计算)。 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):以下是一些示例数据以及现在的查询输出(MAID 和 MCID 是每个表的键):

MainA主A

MAID女佣 Field1字段 1
1 1 apples苹果
2 2 oranges橙子
3 3 grapefuit葡萄柚
4 4 peppers胡椒
5 5 kiwi fruit奇异果
6 6 tomatoes番茄
8 8 avocado鳄梨
9 9 bananas香蕉
10 10 apples苹果

MainC主C

MCID MCID MCField1 MCField1
1 1 bananas香蕉
2 2 peppers胡椒
3 3 peppers胡椒
4 4 tomatoes番茄
5 5 apples苹果
6 6 spinach菠菜
7 7 kale羽衣甘蓝
8 8 apples苹果
9 9 oranges橙子

Query output:查询输出:

Field1字段 1 CountOfMCField1 MCField1 计数
apples苹果 4 4
avocado鳄梨 0 0
bananas香蕉 1 1
grapefuit葡萄柚 0 0
kiwi fruit奇异果 0 0
oranges橙子 1 1
peppers胡椒 2 2
tomatoes番茄 1 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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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