Sort Rows Alternating in SQL Server – How to Guide

sortingsql server

Suppose I have a column x with values A and B. For example:

Row X
1   A
2   A
3   A
4   B
5   B
6   B

Now, I want to sort them into this fashion:

Row X
1   A
2   B
3   A
4   B
5   A
6   B

Of course, I can create a new Column Y. Then assign A rows to odd number (1, 3, 5, …), and B rows to even number (2, 4, 6, …), and then sort with the Y column. But is there an easier way to achieve this?

It will be best if the answer can work with MS SQL.

Best Answer

Try this:

CREATE TABLE SortTest (val char(1))

INSERT INTO SortTest VALUES 
('A'),
('A'),
('A'),
('B'),
('B'),
('B')

SELECT val
FROM SortTest
ORDER BY row_number() OVER (PARTITION BY val ORDER BY val), val