mohsin139
mohsin139

Reputation: 1027

My SQL query order so that no same value from the column come together

I m fetching data from multiple tables and want to sort the result so that no two values come together.

for example query returns the following data.

23

25

26

26

22

22

19

I want this result to be ordered like this so that no two values come consuctivley.

23

25

26

22

26

22

19

Upvotes: 0

Views: 92

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1270391

You actually cannot guarantee that no two values come together (for instance, all values might be the same). But you can distribute them. Here is a method using a subquery and variables:

select t.*
from (select q.*,
             (@rn := if(@v = col, @rn + 1,
                        if(@v := col, 1, 1)
                       )
             ) as rn
      from (query) q cross join
           (select @v := -1, @rn := 0) vars
      order by col
     ) t
order by rn, col;

Upvotes: 1

Related Questions