huahsin68
huahsin68

Reputation: 6989

How to populate 1st row of existing column into new column of 2nd row?

I have a query that generate following output:

| columnA |
-----------
|       5 |
-----------
|       2 |
-----------
|       3 |
-----------
|       4 |
-----------

Is there a solution that I could generate another column which is exactly the same as columnA (lets put a name for it - columnB), and having value from columnA that moving downward. Below is the expecting output:

| columnA | columnB |
---------------------
|       5 |       0 | -> put zero for 1st row
---------------------
|       2 |       5 | -> original value from 1st row of columnA
---------------------
|       3 |       2 | -> original value from 2nd row of columnA
---------------------
|       4 |       3 | -> original value from 3rd row of columnA
---------------------

That's about my question.

Upvotes: 1

Views: 2440

Answers (2)

Ben
Ben

Reputation: 559

In Transact SQL:

       WITH main AS (SELECT ROW_NUMBER() OVER (ORDER BY ColumnA ASC) as rownum, 
                             ColumnA 
                        FROM MainQuery)

     SELECT ISNULL(parent.ColumnA,0) as ColumnA,  
            ISNULL(child.ColumnA,0) as ColumnB 
       FROM main parent FULL OUTER JOIN main child
         ON parent.rownum = child.rownum + 1

Substitute "MainQuery" for the query generating the original columnA.

This produces zeros where the two columns don't overlap (i.e. first and last rows). As mentioned by dice and Mark Bannister, the row positions are meaningless without some kind of ordering. This is captured by the

ROW_NUMBER() OVER (ORDER BY ColumnA ASC)

Which needs to change to how you want the data to be ordered.

Upvotes: 1

svinja
svinja

Reputation: 5576

IN PL/SQL:

-- this gets just the first line
select A A1, null A2 from
    (select A from TABLE)
where rownum = 1
union all
-- this gets the rest of the lines
select Q1.A A1, Q2.A A2 from
    (select A, rownum RN from (select A from TABLE)) Q1    
    join
    (select A, rownum RN from (select A from TABLE)) Q2
    on Q1.RN = Q2.RN + 1

(select A from TABLE) is the inner query that provides the original list. Tested and does what you want. Probably should somehow alias the query that appears multiple times but I don't know how to do that off the top of my head.

You could also replace

(select A, rownum RN from (select A from TABLE))

with

(select A, rownum RN from TABLE))

if you don't mind modifying the original query.

Upvotes: 2

Related Questions