Skip to content
Advertisement

Count occurrences of distinct values

I am trying to find a MySQL query that will display the number of occurrences of an ID value within a year.

Table:

Expected output:

I’m trying with the something along the lines of following sql query, but it gives me nothing like the expected output. It’s the 3rd column im struggling with.

How can i create that 3rd column?

Advertisement

Answer

Scince you are grouping by a_id and year you of course get only 1 distinct value for group. Simply change count(distinct a_id) to count(*).

For example you get group:

Notice in this group distinct a_id values is 1. But you want count of all rows in group. With distinct you will get 1 as occurence in all groups.

EDIT:

Ok, I have missed that you are grouping only by year, so you should group by a_id also. The rest of the answer stays as is. So you end up with:

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