Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Disaggregate count by column content after group by

I’ve got the following table in SQL Server:

ExperienceId EmployeeId ExperienceType
1 1 ‘Work’
2 1 ‘Internal’
3 2 ‘Internal’
4 3 ‘External’
5 3 ‘External’

There are only 3 possible values of ExperienceType: ‘Work’, ‘Internal’ and ‘External’

I’d like to know how many experiences of each type has each employee:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

EmployeeId Work exp Internal exp External exp
1 1 1 0
2 0 1 0
3 0 0 2

I’ve tried this

select EmployeeId, count(*)
from EmployeeExperiences
group by EmployeeId

But that only gives me the total number of experiences per employee, and I don’t know how to disaggregate that by ExperienceType.

>Solution :

One approach is to use conditional aggregation (CASE WHEN inside the aggregation function).

select 
  employeeid,
  count(case when experiencetype = 'Work' then 1 end) as work_exp,
  count(case when experiencetype = 'Internal' then 1 end) as internal_exp,
  count(case when experiencetype = 'External' then 1 end) as external_exp
from employeeexperiences
group by employeeid
order by employeeid;

Another option is to use the PIVOT clause.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading