2012-03-09 72 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) 

這需要改變你想要如何排序數據。

相關問題