【问题标题】:How to populate 1st row of existing column into new column of 2nd row?如何将现有列的第一行填充到第二行的新列中?
【发布时间】:2012-03-09 10:09:52
【问题描述】:

我有一个生成以下输出的查询:

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

这就是我的问题。

【问题讨论】:

  • sql 无序 我想你在某处有一个 id?你怎么知道行的顺序?
  • 试试 RowIndex。我不确定
  • 查询已经应用了过滤器,因此如果第一行是五。抱歉我对这个问题的描述不好。
  • 您能发布您的查询吗?您需要再次执行查询,但顺序相反。但是如何将这两个查询连接在一起???
  • @huahsin68:这是甲骨文吗?此外,dice 的问题是关于排序,而不是过滤 - SQL 中没有固有的排序,因此如果没有要排序的列,对第 1/2/3/n 行的引用是没有意义的。

标签: sql


【解决方案1】:

在 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) 是提供原始列表的内部查询。测试并做你想做的事。可能应该以某种方式为多次出现的查询设置别名,但我不知道该怎么做。

你也可以替换

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

(select A, rownum RN from TABLE))

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

【讨论】:

    【解决方案2】:

    在事务 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”替换为生成原始列 A 的查询。

    这会在两列不重叠的地方产生零(即第一行和最后一行)。正如 dice 和 Mark Ba​​nnister 所提到的,如果没有某种排序,行位置是没有意义的。这是由

    ROW_NUMBER() OVER (ORDER BY ColumnA ASC)
    

    这需要更改为您希望数据的排序方式。

    【讨论】:

      猜你喜欢
      • 2021-10-22
      • 1970-01-01
      • 2011-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多