Ir sounds like you have a bunch of columns and you want to move the values to the left and the NULL
s to the right.
You can do this by counting the number of non-NULL values before each value and then using case
statements to assign values. The following shows the code for four columns:
select (case when col1_n = 1 then col1
when col2_n = 1 then col2
when col3_n = 1 then col3
when col4_n = 1 then col4
end) as col1,
(case when col2_n = 2 then col2
when col3_n = 2 then col3
when col4_n = 2 then col4
end) as col2,
(case when col3_n = 3 then col3
when col4_n = 3 then col4
end) as col3,
(case when col4_n = 4 then col4
end) as col4
from (select t.*,
(case when col1 is not null then 1 end) as col1_n,
((case when col1 is not not null then 1 else 0 end) +
(case when col2 is not null then 1 end)
) as col2_n,
((case when col1 is not not null then 1 else 0 end) +
(case when col2 is not null then 1 else 0 end) +
(case when col3 is not null then 1 end)
) as col3_n,
((case when col1 is not not null then 1 else 0 end) +
(case when col2 is not null then 1 else 0 end) +
(case when col3 is not null then 1 else 0 end) +
(case when col4 is not null then 1 end)
) as col4_n
from t
) t;
You can see this work at SQL Fiddle (here).
If you have a unique id
for each for, you can also unpivot the data, use row_number()
and repivot the data.