Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
601 views
in Technique[技术] by (71.8m points)

sql server 2008 r2 - 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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...