move cells left in sql if left contains null and right contains value

In Sql I am getting the result like below format. Totally i have 6 columns. in 1st row 6th column contains the value and 2nd row 5th & 6th contains the value. But i need to check the every cells if previous column doesn't contain the value means i need that in 1st column.

Actual Result

         a          b           c       d          e    f
                                                        1
                                                   1    2
                                        1          2    3

Expected Result:-

      a          b           c       d          e    f
      1                                             
      1          2                                        
      1          2           3                        

Kindly post some Good answers (I am using SQL server 2008-R2)


Solution 1:

Another way, similar to @Astander's (but using OUTER APPLY instead of PIVOT / UNPIVOT):

SELECT
    a = MIN(CASE WHEN y.rn = 1 THEN y.val END),
    b = MIN(CASE WHEN y.rn = 2 THEN y.val END),
    c = MIN(CASE WHEN y.rn = 3 THEN y.val END),
    d = MIN(CASE WHEN y.rn = 4 THEN y.val END),
    e = MIN(CASE WHEN y.rn = 5 THEN y.val END),
    f = MIN(CASE WHEN y.rn = 6 THEN y.val END)
FROM t
  OUTER APPLY
    ( SELECT
          x.val,
          rn = ROW_NUMBER() OVER (ORDER BY rn)
      FROM
      ( VALUES 
        (a,1), (b,2), (c,3), (d,4), (e,5), (f,6)
      ) x (val, rn) 
      WHERE x.val IS NOT NULL
    ) y 
GROUP BY 
    t.tid ;

Test in SQL-FIddle

Solution 2:

How about something like

DECLARE @Table TABLE(
        a INT,
        b INT,
        c INT,
        d INT,
        e INT,
        f INT
)

INSERT INTO @Table VALUES 
(null,null,null,null,null,10),
(null,null,null,null,10,20),
(null,null,null,10,20,30)

SELECT  *
FROM    @Table

SELECT  SUM([1]) a,
        SUM([2]) b,
        SUM([3]) c,
        SUM([4]) d,
        SUM([5]) e,
        SUM([6]) f
FROM    (
            SELECT  *,
                    ROW_NUMBER() OVER (PARTITION BY ID ORDER BY (SELECT NULL)) ValID
            FROM    (
                        SELECT  *,
                                ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) ID
                        FROM    @Table
                    ) p
                    UNPIVOT
                    (
                        val FOR col IN (a,b,c,d,e,f)
                    ) up
        ) v
        PIVOT (
            SUM(val) FOR ValID IN ([1],[2],[3],[4],[5],[6])
        ) p
GROUP BY    ID

SQL Fiddle DEMO