2017-03-07 81 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和每列一行。

相關問題