具有非基值的数据透视表
Posted
技术标签:
【中文标题】具有非基值的数据透视表【英文标题】:Pivot table with non-cardinal values 【发布时间】:2017-04-20 07:18:56 【问题描述】:我有一张看起来像的桌子
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)。有什么想法吗?
【问题讨论】:
你能看看我刚刚在这里回答了什么(不使用pivot):***.com/questions/43511952/… 【参考方案1】:不需要多次自连接的解决方案:
您可以在ROW_NUMBER()
解析函数的结果上PIVOT
以获得您想要的输出:
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;
【讨论】:
【参考方案2】:请参阅我上面的评论。我尝试为您的表格转换(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;
【讨论】:
以上是关于具有非基值的数据透视表的主要内容,如果未能解决你的问题,请参考以下文章