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
1.1k views
in Technique[技术] by (71.8m points)

postgresql - How to select from SQL table so even and odd rows would be in separate columns?

There is a table ID in my PostgreSQL database.

select * from ID;

ID
1
2
3
4
5
6
7
8

I need to write a query that will give me this output:

id id 
1   2
3   4
5   6
7   8

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

1 Answer

0 votes
by (71.8m points)

There are no such things as even and odd rows. SQL tables represent unordered sets (well technically multi-sets).

Assuming id is the ordering, you can split them using aggregation like this:

select min(id), max(id)
from (select t.*, row_number() over (order by id) - 1 as seqnum
      from t
     ) t
group by floor(seqnum / 2)

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

...