Answer a question

I need to count how many consultants are using a skill through a joining table (consultant_skills), and the challenge is to sum the children occurrences to the parents recursively.

Here's the reproduction of what I'm trying to accomplish. The current results are:

skill_id | count
2        | 2
3        | 1
5        | 1
6        | 1

But I need to compute the count to the parents recursively, where the expected result would be:

skill_id | count
1        | 2 
2        | 2
3        | 1
4        | 2
5        | 2
6        | 1

Does anyone know how can I do that?

Answers

Sqlfiddle Solution

You need to use WITH RECURSIVE, as the Mike suggests. His answer is useful, especially in reference to using distinct to eliminate redundant counts for consultants, but it doesn't drive to the exact results you're looking for.

See the working solution in the sqlfiddle above. I believe this is what you are looking for:

WITH RECURSIVE results(skill_id, parent_id, consultant_id)
AS (
  SELECT skills.id as skill_id, parent_id, consultant_id
  FROM consultant_skills
  JOIN skills on skill_id = skills.id
  
  UNION ALL
  
  SELECT skills.id as skill_id, skills.parent_id as parent_id, consultant_id
  FROM results
  JOIN skills on results.parent_id = skills.id
)
SELECT skill_id, count(distinct consultant_id) from results
GROUP BY skill_id
ORDER BY skill_id

What is happening in the query below the UNION ALL is that we're recursively joining the skills table to itself, but rotating in the previous parent id as the new skill id, and using the new parent id on each iteration. The recursion stops because eventually the parent id is NULL and there is no JOIN because it's an INNER join. Hope that makes sense.

Logo

PostgreSQL社区为您提供最前沿的新闻资讯和知识内容

更多推荐