2017-03-07 17 views
0

我有表,其中一些列包含空值,我的任务是将所有NULL值移动到左侧,因此数值从右移到以相同的顺序排列。如果源行为空,将表数据从一行移动到另一行

(对前)

Column1 Column2 Column3 Column4 
-------------------------------------------- 
NULL  1   NULL  3 
1   NULL  3   2 
1   2   3   NULL 

输出应该是

Column1 Column2 Column3 Column4 
-------------------------------------------- 
1   3   NULL  NULL 
1   3   2   NULL 
1   2   3   NULL 

回答

1

这是一个痛苦,但你可以使用outer apply做到这一点:

select t.id, v.* 
from t outer apply 
    (select max(case when i = 1 then colval end) as col1, 
      max(case when i = 2 then colval end) as col2, 
      max(case when i = 3 then colval end) as col3, 
      max(case when i = 4 then colval end) as col4 
     from (select row_number() over (order by colnum) as i, v.* 
      from (values (1, t.col1), (2, t.col2), (3, t.col3), (4, t.col4) 
       ) v(colnum, colval) 
      where colval is not null 
      ) v 
    ) v; 

我要指出的是,需要做这种类型的转换表明你有一个糟糕的数据模型。单独列中的值可能应该放在另一个表中,每行id和每列一行。

相关问题