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

188
Views
¿Cuál es la forma más fácil de crear una columna que cuente una variable categórica en PostgreSQL? ¿Quizás algún tipo de giro?

Digamos que tengo la siguiente tabla:

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

Me gustaría obtener algo como:

 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

¿Cuál es la forma más fácil de hacer esto?

Pensé en esto:

 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

El problema es que tengo tantos colores que hacer esto sería agotador. hay una manera mas facil?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Hay muchas maneras de lograr esto:

USO DE FILTRO

 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

Violín

tu método

 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

Violín

Uso de tabulaciones cruzadas

 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);

Nota: debe crear una extensión para la tabla de referencias cruzadas utilizando la consulta a continuación

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