非重复计数多列MS Access

时间:2019-03-03 02:23:28

标签: ms-access

我想找到一种使用下表并编写不同计数查询的方法:

Unique Number | Name  | Number | ID
1             | James | 1      | 456
2             | John  | 2      | 456
2             | John  | 3      | 456
2             | John  | 4      | 456
2             | John  | 5      | 457
1             | James | 3      | 457
1             | James | 4      | 456
3             | Ted   | 3      | 457
3             | Ted   | 4      | 456

并希望在ID为456时获得以下查询结果

Unique  | Name  | Number Count
1       | James | 2     
2       | John  | 3      
3       | Ted   | 1   

1 个答案:

答案 0 :(得分:0)

一个简单的聚合查询将通过名称和ID获得Number的计数。

SELECT [Unique Number], [Name], ID, Count(*) AS CountNum FROM table GROUP BY [Unique Number], [Name], ID;'

计算每个名称有多少个唯一ID需要两个查询。首先必须执行一个查询,为每个名称返回DISTINCT ID。

SELECT DISTINCT [Unique Number], [Name], ID FROM tablename;

然后使用该查询来计算总数。

SELECT [Unique Number], [Name], Count(ID) AS CountID FROM Query1 GROUP BY [Unique Number], [Name];

可以嵌套2个查询。
SELECT [Unique Number], [Name], Count(ID) AS CountID FROM (SELECT DISTINCT [Unique Number], [Name], ID FROM tablename) AS Query1 GROUP BY [Unique Number], [Name];