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

252
Vistas
need help writing a query (restructuring the table)

I need to write a select statement that will rewrite the table in the following manner... I'm not sure how to go about this using MySQL.

Example of table

user_id   date         a    b    c     
123456    2020-01-01   1    1    1
234567    2020-03-04   1    0    0
453576    2020-05-05   1    0    1

Desired result

user_id   date        results
123456    2020-01-01  a
123456    2020-01-01  b
123456    2020-01-01  c
234567    2020-03-04  a
453576    2020-05-05  a
453576    2020-05-05  c
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

In MySQL you can unpivot with union all, while filtering on 1 values:

select user_id, date, 'a' as result from mytable where a = 1
union all select user_id, date, 'b' from mytable where b = 1
union all select user_id, date, 'c' from mytable where c = 1
order by user_id, date, result
over 4 years ago · Santiago Trujillo Denunciar

0

If you have a large amount of data or your "table" is really a complex query (say a subquery or view), then unpivoting is usually faster with cross join than with union all:

select t.user_id, t.date, r.result
from t cross join
     (select 'a' as result union all
      select 'b' as result union all
      select 'c' as result 
     ) r
where (t.a = 1 and r.result = 'a') or
      (t.b = 1 and r.result = 'b') or
      (t.c = 1 and r.result = 'c') ;

For a single smallish table, performance probably doesn't matter.

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