问题
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