Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

423
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda