tags:

views:

49

answers:

4

I have a database with the following tables:

Employee (EmpID, FirstName, LastName, RegionID)
EmployeeSkills(EmpID, SkillID) [this is a linking table for the M:N relationship between Employees and skills]
Skills(SkillID, Description)

I need to list the name of the skill that most employees have. I tried doing a max(count(skillID)), sqlserver said that you can't do an aggregate function on an aggregate function. Any other ideas?

Thank you in advance!

+2  A: 

This will return the top SkillsId with how many times it appears:

SELECT TOP 1 SkillID, COUNT(SkillID)
FROM EmployeeSkills
GROUP BY SkillID
ORDER BY COUNT(SkillID) DESC
Oded
Thanks, but I don't need to know how many times each one appears - I need to return the skill that the most employees have.
chama
@chama - answer updated.
Oded
+2  A: 

try this:

SELECT TOP 1
    SkillID, s.Description,COUNT(SkillID) AS CountOf
    FROM EmployeeSkills   e
        INNER JOIN Skills s ON e.SkillID=s.SkillID
    GROUP BY SkillID, s.Description
    ORDER BY 3 DESC
KM
A: 
SELECT s.Description, COUNT(*) from EmployeeSkills es
    INNER JOIN Skills s on s.SkillID = es.SkillID
GROUP BY s.Description ORDER BY COUNT(*) DESC

That will give you a description of the skill, and how many employees have it.

Francisco Soto
You probably want something more like thisSELECT s.Description, COUNT(*) from EmployeeSkills es INNER JOIN Skills s on s.SkillID = es.SkillIDGROUP BY s.DescriptionORDER BY COUNT(*) DESC
Jay
He didnt mention ordering, but you're right and i edited.
Francisco Soto
A: 

The following query will return the skill ID is that is used the most:

  SELECT TOP 1 SkillID, COUNT(SkillID)
    FROM EmployeeSkills
GROUP BY SkillID
ORDER BY COUNT(SkillID) DESC 

You can then use that to get the name of the skill.

Justin Ethier
@Justin - The question is for SQL Server, not MySQL.
Oded