snippetsqlModerate
How to sort rows to appear alternating (e.g. A B A B ... )?
Viewed 0 times
rowshowsortappearalternating
Problem
Suppose I have a column x with values A and B. For example:
Now, I want to sort them into this fashion:
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.
Row X
1 A
2 A
3 A
4 B
5 B
6 BNow, I want to sort them into this fashion:
Row X
1 A
2 B
3 A
4 B
5 A
6 BOf 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), valCode 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), valContext
StackExchange Database Administrators Q#81870, answer score: 10
Revisions (0)
No revisions yet.