Sql 如果列数据为空,则向左推送数据

Sql 如果列数据为空,则向左推送数据,sql,oracle,Sql,Oracle,当我这样做时: SELECT * FROM myTable 表6列 我得到这样的东西: 但我想得到这样的东西: 我尝试了以下方法: 选择合并(NULLIF(col-1'), NULLIF(col-2',), NULLIF(col-3',), NULLIF(col-4',), NULLIF(第5列)、NULLIF(第6列) 这样,我得到第一个非空列,但是如果有,如何得到下一个非空列 还是有其他解决办法 您可以取消pivot数据,按将NULL移动到最后一个位置的列对其进行排序,并再次将其旋转

当我这样做时:

SELECT * FROM myTable
表6列

我得到这样的东西:

但我想得到这样的东西:

我尝试了以下方法:

选择合并(NULLIF(col-1'),
NULLIF(col-2',),
NULLIF(col-3',),
NULLIF(col-4',),
NULLIF(第5列)、NULLIF(第6列)
这样,我得到第一个非空列,但是如果有,如何得到下一个非空列


还是有其他解决办法

您可以取消pivot数据,按将NULL移动到最后一个位置的列对其进行排序,并再次将其旋转到原始形式:

select *
  from (
    select rn, row_number() over (partition by rn order by col) rc, val
      from (select rownum rn, col1, col2, col3, col4, col5, col6 from mytable)
      unpivot (val for col in (col1, col2, col3, col4, col5, col6)))
  pivot (max(val) for rc in (1 col1, 2 col2, 3 col3, 4 col4, 5 col5, 6 col6))


如果您的表中有一些唯一的
id
,请使用它,而不是
rn
。如果要根据数据而不是位置对数据进行排序,请在
行编号()中更改
顺序。Pivot和unpivot需要Oracle 11或更高版本。

您可以使用
case
表达式来实现这一点。这是一种繁琐的逻辑,但可能比在行和列之间移动数据更快:

select (case when col5 is null then col6
             when col4 is null then col5
             when col3 is null then col4
             when col2 is null then col3
             when col1 is null then col2
             else col1
        end) as col1,
       (case when col5 is null then null
             when col4 is null then col6
             when col3 is null then col5
             when col2 is null then col4
             when col1 is null then col3
             else col2
        end) as col2,
       (case when col5 is null then null
             when col4 is null then null
             when col3 is null then col6
             when col2 is null then col5
             when col1 is null then col4
             else col3
        end) as col3,
       . . .
from t;

您的问题表明,您的数据库甚至不在1NF中。考虑规范你的数据库。