具有非基数值的数据透视表

时间:2017-04-20 07:18:57

标签: sql oracle pivot

我有一张类似

的表格
Test   Reader    Result
1      John      1.6
1      Jack      5.2
2      Ursula    2.5
3      Albert    3.0
2      Jack      5.1

我知道每个测试最多可以有3个Readers所以我想创建一个看起来像

的表
Test    Reader_1 Result_1 Reader_2 Result_2 Reader_3 Result_3
1       John     1.6      Jack     5.2      (null)   (null)
2       Ursula   2.5      Jack     5.1      (null)   (null)
3       Albert   3.0      (null)   (null)   (null)   (null)

我环顾四周,看来我需要使用PIVOT表。唯一的问题是我找到了使用序数变量来创建列的示例。在这种情况下,我有预定数量的可能列(3)。有什么想法吗?

2 个答案:

答案 0 :(得分:2)

不需要多个自连接的解决方案:

您可以PIVOT使用ROW_NUMBER()分析函数的结果来获得所需的输出:

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 ) );

<强>输出

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

或者,只使用聚合函数:

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;

答案 1 :(得分:0)

请参阅上面的评论。我试图转换为你的表(T1):

 WITH TX AS (SELECT TEST, READER, RESULT, ROW_NUMBER() OVER (PARTITION BY TEST ORDER BY READER) AS RN
            FROM T1
            )
SELECT T0.TEST
    , TT1.READER AS READER_1
    , TT1.RESULT AS RESULT_1
    , TT2.READER AS READER_2
    , TT2.RESULT AS RESULT_2
    , TT3.READER AS READER_3
    , TT3.RESULT AS RESULT_3
FROM (SELECT DISTINCT TEST FROM T1) AS T0
LEFT JOIN TX TT1 ON T0.TEST = TT1.TEST AND TT1.RN=1
LEFT JOIN TX TT2 ON T0.TEST = TT2.TEST AND TT2.RN=2
LEFT JOIN TX TT3 ON T0.TEST = TT3.TEST AND TT3.RN=3;