【问题标题】:Microsoft Access How to Count the Number of Times a Value and all Permutations of that Value is listed in a Field?Microsoft Access 如何计算一个值和该值的所有排列在字段中列出的次数?
【发布时间】:2020-03-26 15:23:51
【问题描述】:

我有一个表格,在该表格中有一个名为 Results 的字段,其值为 3 位数字。我已经使用 count 函数来报告使用此查询在所述字段中重复值的次数。

SELECT [My Table].Results, Count([My Table].Results) AS [Total Results]
FROM [My Table]
GROUP BY [My Table].Results;

如何使用 count 函数同时返回字段中重复的 3 位数字的所有组合?

例子

Results    Count

123        1
132        1
213        1
789        1
798        1
879        1
897        1

查询后,我希望显示字段中所有值的计数。

Results  Count

123      3
132      3
213      3
789      4
798      4
879      4
897      4

等等

【问题讨论】:

  • 表中是否还有另一个唯一列(如 id)?

标签: sql ms-access ms-access-2016


【解决方案1】:

您可以自行加入表格,并检查加入的记录中是否存在字母

SELECT [parent].Results, Count([parent].Results) AS [Total Results]
FROM (SELECT DISTINCT Results FROM [My Table]) parent, [My Table] child
WHERE 
          child.Results = Left(parent.Results, 1) & Mid(parent.Results, 2, 1) & Right(parent.Results, 1) OR
          child.Results = Left(parent.Results, 1) & Right(parent.Results, 1) & Mid(parent.Results, 2, 1) OR
          child.Results = Mid(parent.Results, 2, 1) & Left(parent.Results, 1) &  Right(parent.Results, 1) OR
          child.Results = Mid(parent.Results, 2, 1) & Right(parent.Results, 1) & Left(parent.Results, 1) OR
          child.Results = Right(parent.Results, 1)  & Left(parent.Results, 1) & Mid(parent.Results, 2, 1) OR
          child.Results = Right(parent.Results, 1) & Mid(parent.Results, 2, 1) & Left(parent.Results, 1)
GROUP BY parent.Results

这将为每个父行复制包含父行的每个符号的子行数,然后计算行数。

或者,您可以使用子查询,但此解决方案的性能可能会更快。

【讨论】:

  • 感谢您的快速回复。当我运行上述查询时,我得到“您尝试执行一个查询,该查询不包含指定表达式‘结果’作为聚合函数的一部分。”对不起,我是这方面的初学者。
  • @NateBorn 看到编辑,那个在我身上,最后一行不包括在内
  • 谢谢,但是当我运行查询时,结果似乎是在计算字符串中的每个数字,而不是组合。这是我的前 10 个总数。 000=138312 001=130242 002=143832 003=140530 004=155844 005=108918 006=138207 007=183330 008=164430 009=127365
  • 啊,如果你有重复的数字,你需要手动迭代组合。因为它只有 3 个符号所以 3!非常可行的组合。如果你想要更多的字符,组合的数量会迅速增加,所以你可能想要使用用户定义的函数。
  • 再次感谢我越来越接近我的目标。我的表由超过 20,000 行组成,其中一个字段的值范围从 000 到 999。假设我的表中有一个 649 的值,我希望计数仅计算 649、694、469、496、946 的值,该 3 位数字的所有组合。所以说,在我的字段中,我的表中只有上述六个值,每次出现的总数最终都会为 6。但我需要为每 3 位数字 000-999 完成此操作。
猜你喜欢
  • 1970-01-01
  • 2021-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多