Ebrahim Tavasoli
Ebrahim Tavasoli

Reputation: 45

Custom sorting in sql

I have a table with a column named category. the data in it is 1, 2, 3 so every row has a category.

I need sort data by category like this

1,2,3,1,2,3,1,2,3,....

then if some category finished sorting continues like this

1,2,3,1,2,3,1,3,1,3,1,1,1,1,....

I am using PostgreSQL.

thanks for your answers

Upvotes: 0

Views: 66

Answers (3)

Red Devil
Red Devil

Reputation: 2393

select ID from (
select *,row_number() over ( partition by id order by id ) rn from Yourtable  
) I
order by  rn,id

Upvotes: 0

Mustafa BYKSY
Mustafa BYKSY

Reputation: 95

You can use like this:

SELECT
   c,
   RANK () OVER ( 
      ORDER BY c 
   ) rank_number 
FROM
   ranks;

Results:

For more information: http://www.postgresqltutorial.com/postgresql-rank-function/

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1269543

You can use window functions:

order by row_number() over (partition by category order by category)

You can specify whatever you want for the order by. For instance, if you want a random ordering:

order by row_number() over (partition by category order by random())

Upvotes: 2

Related Questions