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

306
Views
Cómo pivotar en postgresql

Tengo una tabla como la siguiente y me gustaría transformarla.

 year month week type count 2021 1 1 A 5 2021 1 1 B 6 2021 1 1 C 7 2021 1 2 A 0 2021 1 2 B 8 2021 1 2 C 9

Me gustaría pivotar de la siguiente manera.

 year month week ABC 2021 1 1 5 6 7 2021 1 2 0 8 9

Intenté como la siguiente declaración, pero devolvió muchas columnas nulas. Y me pregunto si debo agregar columnas una por una cuando se agregue un nuevo tipo.

 select year, month, week, case when type in ('A') then count end as A, case when type in ('B') then count end as B, case when type in ('C') then count end as C, from table

Si alguien tiene una opinión, por favor hágamelo saber. Gracias

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

demostración: db<>violín

Puede usar la cláusula FILTER :

 SELECT year, month, week, MAX("count") FILTER (WHERE type = 'A') as A, -- 2 MAX("count") FILTER (WHERE type = 'B') as B, MAX("count") FILTER (WHERE type = 'C') as C FROM mytable GROUP BY year, month, week -- 1 ORDER BY year, month, week

o puede usar la cláusula CASE :

 SELECT year, month, week, MAX (CASE WHEN type = 'A' THEN "count" END) AS A, MAX (CASE WHEN type = 'B' THEN "count" END) AS B, MAX (CASE WHEN type = 'C' THEN "count" END) AS C FROM mytable GROUP BY year, month, week ORDER BY year, month, week
  1. En ambos casos, debe realizar una acción GROUP BY .
  2. Esto hace necesaria una función de agregación, como MAX() o SUM() . Finalmente, debe aplicar un tipo de filtro ( CASE o FILTER ) para agregar solo los datos relacionados.

Además : tenga en cuenta que las palabras count , year , month , week son palabras clave de SQL . Para evitar cualquier complicación, debe pensar en otros nombres de columna.

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!