简体   繁体   中英

Count Distinct in MS Access - How to count number of accounts with at least one activity of a certain type?

I have a list of activities where one field is AccountName indicating the name of the person. There is another field called ActivityType .

Basically I want to return the number of accounts that have at least one ActivityType that is equal to RET (indicating a returned item). Since a person may have multiple returns in a given year I don't want to count the number of returns total, just the number of accounts that have at least one RET.

I've tried various combinations of select statements, count statements, having statements, it's just not working right.

Here is what I tried:

Select DISTINCT Count(Activities.AccountName) AS CountOfAccountName
FROM Activities
GROUP BY Activities.ActivityType
HAVING (Activities.ActivityType = "RET")

But this seems to return a much larger number than if I just do the select statement:

SELECT DISTINCT Activities.AccountName
FROM Activities
WHERE (Activities.ActivityType = "RET")

I think you need a simple COUNT and GROUP BY function. Since Access doesn't allow Count Distinct , You need to first select distinct records and then count them -

SELECT Count(T.AccountName) AS CountOfAccountName
FROM (SELECT AccountName
      FROM Activities
      WHERE Activities.ActivityType = 'RET'
      GROUP BY AccountName) T;

This will filter only those records having ActivityType = 'RET' and then will count the distinct AccountName.

Use a subquery:

SELECT Count(*) AS ActiveAccounts
FROM
    (SELECT DISTINCT AccountName
    FROM Activities
    WHERE ActivityType = "RET")

If activity/types cannot be duplicated, then you can simply use:

select count(*) AS CountOfAccountName
from Activities
where Activities.ActivityType = "RET";

If they can be, then you need a subquery as shown in other answers.

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