3

How can I order by a Select by a sequence?

I mean, I have these datas:

column_1   |   column_2
    1      |      a    
    2      |      b    
    3      |      c    
    4      |      d
    4      |      e    
    3      |      f    
    1      |      g    
    2      |      h    

And I want to order by 1-4 group, I mean:

column_1   |   column_2
    1      |      a    
    2      |      b    
    3      |      c    
    4      |      d
    1      |      g    
    2      |      h 
    3      |      f    
    4      |      e    

I would like column_1 ordered by 1,2,3,4 sequence of values then 1,2,3,4 again.
I mean, I don't want ordering this way: 1,1,2,2,3,3,4,4...

[[EDIT]]
The column_2 should by Asc, I mean: Order By column_2 Asc

[[EDIT 2]]
I will use this Select on SQLite. I'm trying to find a way using just SQL commons commands.

Sql Fiddle

Does anyone know how it's possible?

Felipe M
  • 449
  • 1
  • 3
  • 14

1 Answers1

1

If you want to order by a sequence, you really want to enumerate each value in column 1, independently for each value. For example:

1     1
2     1
3     1
4     1
4     2
3     2
2     2
1     2
5     1
5     2
5     3

I'm not sure if there is an easy way to do this in SQLite. In MySQL, you would use variables. In other databases, window functions. You can accomplish this correlated subqueries:

select column_1, column_2
from (select t.*,
             (select count(*) from table t2 where t2.column_1 = t.column_1 and t2.rowid <= t.rowid
             ) as seqnum
      from table t
     ) t
order by seqnum, column_1;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786