[英]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. 有没有一个解决方案,我可以生成另一列与columnA完全相同(让我们为它命名 - columnB),并从columnA向下移动的值。 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. 这是关于我的问题。
IN PL/SQL: 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. (从TABLE中选择A)是提供原始列表的内部查询。 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. 如果您不介意修改原始查询。
In Transact SQL: 在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. 将“MainQuery”替换为生成原始columnA的查询。
This produces zeros where the two columns don't overlap (ie 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. 哪个需要更改为您希望如何订购数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.