Search code examples
sqlcountinner-joinaggregate-functionswindow-functions

I Can't use COUNT and have any other code running in the file (SQL)


I'm Trying to make code where an employees are filtered by their skills, with if the employee has one or no skills, they don't come up. I got the first half done, getting them filtered by their skills, but whenever I try to add a COUNT, it doesn't work unless it's running entirely on its own!

Select k.employeeID, COUNT (*)
FROM EmployeeSkills_t k
GROUP BY k.employeeID
HAVING COUNT(*)>1

Does not want to intergrate with

select e.Employeename, s.skillDescription
from EmployeeSkills_t k
INNER JOIN Employee_t e ON k.EmployeeID = e.EmployeeID
INNER JOIN Skill_t s ON k.skillID=s.skillID 
ORDER BY e.Employeename, skillDescription

Solution

  • No need for to join an aggregate query. Instead, starting from your existing query that lists the skills of each employee, you can do a window count() to compute how many skills each of them has. All that is left to do is to filter :

    select *
    from (
        select e.employeename, s.skilldescription,
            count(*) over(partition by e.employeeid) as cnt_employee_skills
        from employeeskills_t k
        inner join employee_t e on k.employeeid = e.employeeid
        inner join skill_t s on k.skillid=s.skillid 
    ) t
    where cnt_employee_skills > 1
    order by employeename, skilldescription