Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

434
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda