Oracle
 sql >> Database >  >> RDS >> Oracle

Tabella pivot con valori non cardinali

Una soluzione che non richiede più auto join:

Puoi PIVOT sul risultato di ROW_NUMBER() funzione analitica per ottenere l'output desiderato:

SELECT *
FROM   (
  SELECT t.*,
         ROW_NUMBER() OVER ( PARTITION BY test ORDER BY ROWNUM ) AS rn
  FROM   your_table t
)
PIVOT ( MAX( Reader ) AS reader, MAX( result ) AS result FOR rn IN ( 1, 2, 3 ) );

Risultato :

TEST 1_READER 1_RESULT 2_READER 2_RESULT 3_READER 3_RESULT
---- -------- -------- -------- -------- -------- --------
   1 John          1.6 Jack          5.2
   2 Ursula        2.5 Jack          5.1
   3 Albert        3.0

Oppure, semplicemente usando le funzioni di aggregazione:

SELECT test,
       MAX( CASE rn WHEN 1 THEN reader END ) AS reader_1,
       MAX( CASE rn WHEN 1 THEN result END ) AS result_1,
       MAX( CASE rn WHEN 2 THEN reader END ) AS reader_2,
       MAX( CASE rn WHEN 2 THEN result END ) AS result_2,
       MAX( CASE rn WHEN 3 THEN reader END ) AS reader_3,
       MAX( CASE rn WHEN 3 THEN result END ) AS result_3
FROM   (
  SELECT t.*,
         ROW_NUMBER() OVER ( PARTITION BY test ORDER BY ROWNUM ) AS rn
  FROM   your_table t
)
GROUP BY test;