I have a few columns as such:
Category | Rank |
---|---|
VIDEOS | 19 |
VIDEOS | 20 |
BUSINESS | 10 |
ENTERTAINMENT | 13 |
WORLD | 14 |
WORLD | 15 |
BUSINESS | 25 |
I want to get results such that no 2 category values should appear consecutively. They can be repeated at a later row. Just that they should not be one after another. ex: videos in first row and videos in second row need re-arranging. So does world.
Category | Rank |
---|---|
VIDEOS | 19 |
BUSINESS | 10 |
ENTERTAINMENT | 13 |
WORLD | 14 |
BUSINESS | 25 |
VIDEOS | 20 |
WORLD | 15 |
Is it possible to make it alternating? I am working with a PostgreSQL server.
CodePudding user response:
Sample Query:
select t1.cat, t1.rank from (
select
cat,
rank,
row_number() over (partition by cat) as num
from your_table
) t1
order by t1.num;
Result:
VIDEOS 19
ENTERTAINMENT 13
BUSINESS 10
WORLD 14
BUSINESS 25
VIDEOS 20
WORLD 15