locked
plz help me.. RRS feed

  • Question

  • Input:

    Table 1:

    col1    col2     col3     col4

    A   B      Null      Null 

    C        D        Null       Null 

    Null   Null       E           F

    I want ouput table like this:

    Table1:

    col1       col2        col3         col4

    A            B             E             F

    C           D             Null        Null

    Monday, May 21, 2012 6:05 AM

Answers

  • Perhaps this might help as a starting point:

    declare @test table
    ( col1 char(1), col2 char(1), col3 char(1), col4 char(1));
    insert into @test
    select 'A','B',null,null union all select 'C','D',null,null union all
    select null,null,'E','F'
    ;
    with cte1 as
    ( select
        col1, col2,
    	row_Number() over( order by col1, col2
    	) as Rn
      from @test
      where col1 is not null
    ), cte2 as
    ( select
        col3, col4,
    	row_Number() over( order by col3, col4
    	) as Rn
      from @test
      where col3 is not null
    )
    select
      col1, col2, col3, col4 
    from cte1 a
    left join cte2 b
      on b.rn = a.rn;
    /* -------- Output: --------
    col1 col2 col3 col4
    ---- ---- ---- ----
    A    B    E    F
    C    D    NULL NULL
    */

    • Proposed as answer by Sanil Mhatre Monday, May 21, 2012 4:38 PM
    • Marked as answer by Maggie Luo Tuesday, May 29, 2012 2:44 AM
    Monday, May 21, 2012 12:02 PM

All replies

  • Hello,

    Can you please explain the logik, how to get the required result? By your sample data I don't get/see the logic.


    Olaf Helper
    * cogito ergo sum * errare humanum est * quote erat demonstrandum *
    Wenn ich denke, ist das ein Fehler und das beweise ich täglich
    Blog Xing

    Monday, May 21, 2012 6:20 AM
  • Perhaps this might help as a starting point:

    declare @test table
    ( col1 char(1), col2 char(1), col3 char(1), col4 char(1));
    insert into @test
    select 'A','B',null,null union all select 'C','D',null,null union all
    select null,null,'E','F'
    ;
    with cte1 as
    ( select
        col1, col2,
    	row_Number() over( order by col1, col2
    	) as Rn
      from @test
      where col1 is not null
    ), cte2 as
    ( select
        col3, col4,
    	row_Number() over( order by col3, col4
    	) as Rn
      from @test
      where col3 is not null
    )
    select
      col1, col2, col3, col4 
    from cte1 a
    left join cte2 b
      on b.rn = a.rn;
    /* -------- Output: --------
    col1 col2 col3 col4
    ---- ---- ---- ----
    A    B    E    F
    C    D    NULL NULL
    */

    • Proposed as answer by Sanil Mhatre Monday, May 21, 2012 4:38 PM
    • Marked as answer by Maggie Luo Tuesday, May 29, 2012 2:44 AM
    Monday, May 21, 2012 12:02 PM