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

191
Visualizações
What's the easiest way of creating a column counting a categorical variable on PostgreSQL? Maybe some sort of pivoting?

Let's say I have the following table:

Id    color
A00   blue
A00   blue
A99   red
A99   blue
A95   yellow
A97   green

I would like to get something like:

Id    blue    red    yellow    green
A00   2       0      0         0     
A99   1       1      0         0
A95   0       0      1         0
A97   0       0      0         1

What's the easiest way of doing this?

I thought about this:

select Id,
       sum(case when color='blue' then 1 else 0 end) as blue,
       sum(case when color='red' then 1 else 0 end) as red,
       .
       .
       .
from table 

The problem is that I have so many colours that doing this would be exhausting. Is there an easier way?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

There are many ways to achieve this:

USING FILTER

select 
id,
count(*) filter (where color='blue') as "Blue",
count(*) filter (where color='red') as "Red",
count(*) filter (where color='yellow') as "Yellow",
count(*) filter (where color='green') as "Green"
 from samp
group by id

Fiddle

Your Method

select 
id,
sum(case when color='blue' then 1 else 0 end) as "Blue",
sum(case when color='red' then 1 else 0 end) as "Red",
sum(case when color='yellow' then 1 else 0 end) as "Yellow",
sum(case when color='green' then 1 else 0 end) as "Green"
 from samp
group by id

Fiddle

Using Crosstab

select * from crosstab(
'select id, color,count(*) from samp group by id,color order by id,color', 
'select distinct color from samp order by color'
) 
as ct("ID" varchar, "blue" int,"green" int,"red" int,"yellow" int);

Note: you have to create extension for crosstab using below query

CREATE EXTENSION IF NOT EXISTS tablefunc;
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