首页 > 解决方案 > 将列值向左切换

问题描述

我有一个如下表:

      Column A           Column B            Column C
     ----------          ---------         -----------
         1                   1                 2
         4                   3                 4
         3                  null               2
         12                  12                12
         15                  7                 7 
         8                   9                 6
         null                2                 2
         null                null              3

我需要将每列值从右向左移动,直到每列除了空值之外都有不同的值。输出必须是这样的:

      Column A           Column B            Column C
     ----------          ---------         -----------
         1                   2                null
         4                   3                null
         3                   2                null
         12                  null             null
         15                  7                null 
         8                   9                6
         2                   null             null
         3                   null             null

我怎样才能用最简单的方法做到这一点?

谢谢,

标签: sqloracle

解决方案


unpivot、pivot 和条件排序的这种组合返回所需的输出:

with 
  nn as (
   select id, col, case rn when 1 then val end val
   from (
     select id, col, val, row_number() over (partition by id, val order by col) rn
     from (select rownum id, a, b, c from t)
     unpivot (val for col in (a, b, c) ) ) ),
   mov as (
     select id, val, 
            row_number() over (partition by id 
                               order by case when val is not null then col end ) rn 
     from nn )
select * from mov pivot (max(val) for rn in (1 a, 2 b, 3 c))

小提琴手

子查询nn删除重复值,mov基于条件排序的子查询将它们向上移动。然后枢轴将行转置为列,因为它们在第一步中未被转置。


推荐阅读