一尘不染

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

sql

我有一张桌子,看起来像

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)。有任何想法吗?


阅读 168

收藏
2021-05-05

共1个答案

一尘不染

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

您可以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;
2021-05-05