user1268559
user1268559

Reputation: 223

Count distinct query MS Access

It seems that we can not use Count (Distinct column) function in MS Access. I have following data and expected result as shown below

Looking for MS Access query which can give required result.

Data

ID     Name     Category    Person  Office
1      FIL       Global     Ben     london
1      FIL       Global     Ben     london
1      FIL       Overall    Ben     Americas
106   Asset      Global     Ben     london
156   ICICI      Overall    Rimmer  london
156   ICICI      Overall    Rimmer  london
188   UBS       Overall     Rimmer  london
9    Fund      Global       Rimmer  london

Expected Result

Person  Global_Cnt  Overall_Cnt    
Ben          2         1
Rimmer       1         2

Upvotes: 1

Views: 7488

Answers (4)

FA LE TI NO
FA LE TI NO

Reputation: 65

select count(column) as guessTable
from
(
    select distinct column from Table
)

Upvotes: 0

Eoin2211
Eoin2211

Reputation: 911

MS Access-Engine does not support

 SELECT count(DISTINCT....) FROM ...

You have to do it like this:

 SELECT count(*) 
 FROM
 (SELECT DISTINCT Name FROM table1)

Its a little workaround... you're counting a DISTINCT selection.

Upvotes: 0

HansUp
HansUp

Reputation: 97101

Use a subquery to select the distinct values from your table.

In the parent query, GROUP BY Person, and use separate Count() expressions for each category. Count() only counts non-Null values, so use IIf() to return 1 for the category of interest and Null otherwise.

SELECT
    sub.Person,
    Count(IIf(Category = 'Global', 1, Null)) AS Global_Cnt,
    Count(IIf(Category = 'Overall', 1, Null)) AS Overall_Cnt
FROM
    (
        SELECT DISTINCT ID, Category, Person
        FROM YourTable
    ) AS sub
GROUP BY sub.Person;

I was unsure which fields identify your unique values, so chose ID, Category, and Person. The result set from the query matches what you asked for; change the SELECT DISTINCT field list if it doesn't fit with your actual data.

Upvotes: 1

umirza47
umirza47

Reputation: 940

When creating a query in Microsoft Access, you might want to return only distinct or unique values. There are two options in the query's property sheet, "Unique Values" and "Unique Records":

DISTINCT and DISTINCTROW sometimes provide the same results, but there are significant differences:

DISTINCT DISTINCT checks only the fields listed in the SQL string and then eliminates the duplicate rows. Results of DISTINCT queries are not updateable. They are a snapshot of the data.

DISTINCT queries are similar to Summary or Totals queries (queries using a GROUP BY clause).

DISTINCTROW DISTINCTROW, on the other hand, checks all fields in the table that is being queried, and eliminates duplicates based on the entire record (not just the selected fields). Results of DISTINCTROW queries are updateable.

Read More...

Upvotes: 0

Related Questions