Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
93 views
in Technique[技术] by (71.8m points)

sql - How to find out below output using oracle query

Input:

col1  col2
------------
1 A
2 1
3 B
4 2
5 C
6 Null

Output i want

Col1 Col2
__________
A  1
B  2
C Null
question from:https://stackoverflow.com/questions/65847744/how-to-find-out-below-output-using-oracle-query

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Oh, I see. Assuming there are no gaps in col1, you can use aggregation using arithmetic:

select max(case when mod(id, 2) = 0 then col2 end),
       max(case when mod(id, 2) = 1 then col2 end)
from t
group by floor((id - 1) / 2);

Another method uses lead():

select col2, next_col2
from (select t.*, lead(col2) over (order by id) as next_col2
      from t
     ) t
where mod(id, 2) = 1;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...