Skip to content
Advertisement

SQL: How do I get a filtered count for each distinct row in a table?

Note: this is different from questions that ask “I want a count for each distinct row in a table” which has been answered numerous times. This is a filtered count, so the counting part of the query needs a more complex WHERE clause. Consider this dataset:

I want to query this table and know the number of users over the age of 13 for each distinct customer_id. So the result would be:

I’ve tried something like this but it just runs forever, so I think I’m doing it wrong:

Advertisement

Answer

Just use conditional aggregation:

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement