Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

429
Views
How to sum children occurrences from a joining table in Postgres?

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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!