2017-03-07 5 views
0

いくつかの列にはNULL値が含まれています。NULLの値をすべて左側に移動するように割り当てられているため、数値は右から同じ順序で残っています。 (EX用)ソース行が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; 

私はあることに注意する必要がありこのタイプの変換を行う必要がある場合は、データモデルが貧弱であることが示唆されます。別々の列の値は、おそらく別の表にあり、1行はidと1列になります。

関連する問題