MySQL Sorting by turns

别等时光非礼了梦想. 提交于 2019-12-23 06:29:27

问题


I want to sort the following data items in the order they are presented below :

id | res
--------
1     A
2     A
3     A
4     A
5     A
6     B
7     B
8     B
9     B
10    B
11    C
12    C
13    C
14    C
15    C

And i want the output is :

res
---
A
B
C
A
B
C
A
B
C
A
B
C
A
B
C

Any tricks to make it sort more properly?

Many Thanks!


回答1:


You can order by the "rank" within the group. The rank can be calculated using a self join and counting the entries with lesser ids.

select t1.id, t1.res
from mytable t1
join mytable t2
  on  t2.res = t1.res
  and t2.id <= t1.id
group by t1.id, t1.res
order by count(*), t1.res

http://rextester.com/ICHZNN18920



来源:https://stackoverflow.com/questions/40060102/mysql-sorting-by-turns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!