HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlModerate

How to sort rows to appear alternating (e.g. A B A B ... )?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
rowshowsortappearalternating

Problem

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.

Solution

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

Code Snippets

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

Context

StackExchange Database Administrators Q#81870, answer score: 10

Revisions (0)

No revisions yet.