Mysql
 SQL >> Datenbank >  >> RDS >> Mysql

Spaltenwerte mit SQL Window Functions in Zeilen pivotieren

Mit Window Functions und bedingter Aggregation können Sie Werte drehen:

SELECT rn,
       MAX(CASE WHEN occupation = 'Doctor' THEN name END) AS doctor,
       MAX(CASE WHEN occupation = 'Singer' THEN name END) AS singer,
       MAX(CASE WHEN occupation = 'Actor' THEN name END) AS actor
FROM (
    SELECT t.*, ROW_NUMBER() OVER (PARTITION BY occupation ORDER BY name) AS rn
    FROM mytable t
) x
GROUP BY rn;

Die Unterabfrage nummeriert Personen pro Beruf, die äußere Abfrage pivotiert sie in Spalten.