[英]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 ![]() |
apples![]() |
2 ![]() |
oranges![]() |
3 ![]() |
grapefuit![]() |
4 ![]() |
peppers![]() |
5 ![]() |
kiwi fruit![]() |
6 ![]() |
tomatoes![]() |
8 ![]() |
avocado![]() |
9 ![]() |
bananas![]() |
10 ![]() |
apples![]() |
MainC主C
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.