簡體   English   中英

如何將現有列的第一行填充到第二行的新列中?

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

我有一個生成以下輸出的查詢:

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

有沒有一個解決方案,我可以生成另一列與columnA完全相同(讓我們為它命名 - columnB),並從columnA向下移動的值。 以下是期望的輸出:

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

這是關於我的問題。

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

(從TABLE中選擇A)是提供原始列表的內部查詢。 經過測試並做你想做的事。 可能應該以某種方式對多次出現的查詢進行別名,但我不知道如何做到這一點。

你也可以替換

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

(select A, rownum RN from TABLE))

如果您不介意修改原始查詢。

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

哪個需要更改為您希望如何訂購數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM