sql >> Base de Datos >  >> RDS >> Mysql

SQL gira los valores de la columna

Puede usar funciones de ventana y agregación condicional:

select
    rn,
    max(case when occupation = 'Doctor' then name end) doctor,
    max(case when occupation = 'Singer' then name end) singer,
    max(case when occupation = 'Actor'  then name end) actor
from (
    select t.*, row_number() over(partition by occupation order by name) rn
    from mytable t
)
group by rn

La subconsulta clasifica a las personas que tienen la misma ocupación por nombre. Luego puede usar esa información para generar las filas y acceder al nombre correspondiente para cada ocupación con un agregado condicional.

Sin funciones de ventana, es diferente. Si sus datos no son demasiado grandes, una opción emula el número de fila con una subconsulta:

select
    rn,
    max(case when occupation = 'Doctor' then name end) doctor,
    max(case when occupation = 'Singer' then name end) singer,
    max(case when occupation = 'Actor'  then name end) actor
from (
    select t.*, 
        (
            select count(*) 
            from mytable t1 
            where t1.occupation = t.occupation and t1.name <= t.name
        ) rn
    from mytable t
)
group by rn