Skip to content
Advertisement

Count number of students per one role SQL

I have a table students with student id, course id and role number looking like this (ordered by student_id):

How to count number of students for each role? If student is enrolled in multiple courses with the same role number, then count this as one. The expected output for above table would be similar to this:

So in the above table sample, the partition would be by student_id:

I’m not sure if this is possible to achieve with the current table. I have implemented PARTITION BY, but I can only count number of distinct roles per students, which is not correct:

The above query outputs something like this (I included roles to illustrate the error):

Advertisement

Answer

Aggregate by role and take the distinct count of students:

You seem to want to report each role only once, which implies that the GROUP BY option above is what you want. Note that using COUNT as an analytic function will result in every record from the original students table being reported, which is not what you want here.

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