How can I count distinct values within each group?
Quick answer
Group rows by the value that identifies each group, then apply COUNT(DISTINCT value_column) to count unique, non-NULL values in each group. For example, GROUP BY event_id with COUNT(DISTINCT attendee_id) counts each attendee once per event. COUNT(*) gives a different result: it counts every row in the group, including rows where attendee_id is NULL. [S1]
The question, the details, the next step.
A practical checklist
Decide what one result row represents, such as one event.
Group by the column that identifies that entity, such as event_id.
Use COUNT(DISTINCT value_column) for unique, non-NULL values within each group.
Check how NULL values should be treated; this count excludes them.
Compare COUNT(*) and the distinct count on sample rows containing duplicates.
Confirm that the grouping key does not combine separate entities unintentionally.
A few more useful answers
Does COUNT(DISTINCT attendee_id) count NULL attendee IDs?
No. In SQLite, COUNT(DISTINCT X) counts distinct non-NULL values of X, so NULL attendee IDs are excluded. [S1]
What does COUNT(*) count when I use GROUP BY?
It counts all rows in each group, including rows with duplicate values or NULLs in the attendee column. [S1]
Can I count distinct values for a different column?
Yes. Replace attendee_id with the column whose distinct, non-NULL values you want to count, while keeping the grouping column that defines each result row.
Sources
References used for this guide.
- [S1] SQLite built-in aggregate functions: COUNT and DISTINCT sqlite.org · Checked
