2012-03-09 99 views
1

我有产生以下输出的查询:如何将现有列的第一行填充到第二行的新列中?

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

有没有办法,我可以生成另一列是完全一样columnA一个解决方案 - 从(让我们把一个名字为它columnB),并具有价值柱A向下移动。下面是期待输出:

| 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 
--------------------- 

这是关于我的问题。

+3

sql正在无序我推测你有一个id在那里?你怎么知道行的顺序? – dice 2012-03-09 10:13:56

+0

尝试RowIndex.I不确定 – joshua 2012-03-09 10:17:52

+0

该查询已应用过滤器,因此如果第一行是五。对不起,我对这个问题的描述很糟糕。 – huahsin68 2012-03-09 10:18:57

回答

2

在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 

(选择表A)是提供原始列表内的查询。测试并做你想要的。可能应该以某种方式别名多次出现的查询,但我不知道如何做到这一点。

你也可以用

(select A, rownum RN from TABLE)) 

更换

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

,如果你不介意修改原始查询。

1

在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 

替代 “MainQuery” 为查询生成的原始columnA。

这产生了两列不重叠的零(即第一行和最后一行)。正如骰子和马克班尼斯特所提到的那样,没有某种排序,排的位置是毫无意义的。这是由

ROW_NUMBER() OVER (ORDER BY ColumnA ASC) 

这需要改变你想要如何排序数据。

相关问题