0

So, let say I have this data

id | value | group
1  | 100   | A
2  | 120   | A
3  | 150   | B
4  | 170   | B

I want to sort it so it become like this

id | value | group
1  | 100   | A
3  | 150   | B
2  | 120   | A
4  | 170   | B

there will be more group than that, so if I the data ordered the group like (A,C,B,D,B,C,A), it will become (A,B,C,D,A,B,C)

7
  • 4
    What is the logic behind this sort order? Letters in order, A - Z, one at a time, and then start again, until no letters are left? What makes you pick one A over another A? Remember that database rows have no order to them, so I guess that choice is based on the id? One last burning question: WHY? Commented May 3, 2019 at 18:04
  • To @KIKOSoftware 's question, why is 1 | 100 | A before 2 | 120 | A? Because of the id or because of the value? What if they have the same value? Commented May 3, 2019 at 18:09
  • the 'value' or the 'id' doesn't matter here. the data sorted by the 'group'. so if the 'group' unique data is (A,B,C,D), then it should return data in that order. Commented May 3, 2019 at 18:15
  • So 2 | 120 | A can come before 1 | 100 | A? Commented May 3, 2019 at 18:18
  • @AbraCadaver yes. only 'group' column order matters Commented May 3, 2019 at 18:20

2 Answers 2

1

You can add a counter column to the table, which will be used to sort the table:

select t.id, t.value, t.`group`
from (
  select t.id, t.value, t.`group`,
  (select count(*) from tablename 
   where `group` = t.`group` and id < t.id) counter
  from tablename t
) t
order by t.counter, t.`group`

See the demo.
Results:

| id  | value | group |
| --- | ----- | ----- |
| 1   | 100   | A     |
| 3   | 150   | B     |
| 2   | 120   | A     |
| 4   | 170   | B     |
Sign up to request clarification or add additional context in comments.

Comments

0

You can approach this as

SELECT *
FROM `tablename`
ORDER BY 
row_number() OVER (PARTITION BY `group` ORDER BY `group`), `group`

enter image description here

3 Comments

Ah, is there an OVER in MySQL now?
@KIKOSoftware screen shoot attached

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.