Reputation: 21
I have a member identifier reference number in one field and a date in another field.
The database contains rows where the member identifier appears more than once. For a given member, who can have multiple records (rows), sometimes the date is the same and sometimes it is different.
I want to count the number of unique instances of date against the member.
If a member has three records and they all have the same date, I want the query to return the value 1.
If a member has three records and two are 01/01/2005 and the third is 10/06/2003, I want the query to return the value 2.
If a member has three records and three different dates I want the query to return the value 3.
Upvotes: 1
Views: 1921
Reputation: 2265
What you want is a GROUP BY
clause with the aggregate function COUNT
... but on a subquery that uses SELECT DISTINCT
to get unique User ID/Date combinations first.
With this record set:
You can either use the Query Designer to make two queries, the first one being:
And the second, which uses the first query you created, being:
To get the output you want:
Alternatively, if you're like me and prefer to work with raw SQL, you can just use this SQL in a single query:
SELECT DistinctDates.UserID, Count(DistinctDates.TheDate) AS NumDates
FROM (SELECT DISTINCT Table1.UserID, Table1.TheDate FROM Table1) AS DistinctDates
GROUP BY DistinctDates.UserID;
One thing extra that I'd like to note, which I learned just now off of W3Schools's SQL SELECT DISTINCT Statement page, is that most other RDBMS engines may allow you to use DISTINCT
on fields in a query. However, The MSAccess/Jet Engine doesn't support that syntax. If you're in another DB engine at any point, you could just do this:
SELECT Table1.UserID, COUNT(DISTINCT Table1.TheDate) AS NumDates FROM Table1;
Upvotes: 1
Reputation: 55806
You can use:
Select MemberID, Count(*) As DateCount
From (Select Distinct MemberID, DateField From YourTable)
Group By MemberID
Upvotes: 2