Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sql Order By Value

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?

like image 933
Felipe M Avatar asked Dec 04 '25 02:12

Felipe M


1 Answers

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;
like image 137
Gordon Linoff Avatar answered Dec 06 '25 15:12

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!