Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering values in SQL

Tags:

mysql

Lessons Table

Is there any way that could sort the values on the table so I get one week (Monday-Sunday) and then next week, like it is described next

Monday .......
Tuesday ......
Wednesday ....
Thursday .....
Friday .......
Saturday .....
Sunday .......

Monday .......
Tuesday ......
Wednesday ....
Thursday .....
Friday .......
Saturday .....
Sunday .......

Monday .......
Tuesday ......
Wednesday ....
Thursday .....
Friday .......
Saturday .....
Sunday .......

If it is necessary I can modify the table structure. I hope it makes sense.

like image 539
Gacci Avatar asked Nov 10 '22 09:11

Gacci


1 Answers

SELECT lid, ordinal,DAY, class, teaher, STARTS, ENDS  FROM (
   SELECT lid, ordinal, DAY, class, teaher, STARTS, ENDS,
   IF(@myvar = 0 OR @myvar = ordinal, @counter := @counter + 1, @counter := 1) sequence,  
   @myvar := ordinal FROM mytable 
   JOIN (SELECT @myvar := 0, @counter := 0 ) a
   ORDER BY ordinal , lid) b 
ORDER BY sequence, ordinal ,  lid

Try this query. I have not tried it locally.

Similar question which I have answered is here

EDIT :

To answer the questions raised in the comments below

1) How does it work?

Take the inner query and execute it separately. It assigns a sequence for all rows in a way that whenever the ordinal repeats, it increments the counter. When a new ordinal is found, it reset the counter to 1. Now with the help of outer query, it orders the result by the sequence and show the result. It would be best explained if you run these queries separately and analyse the result at each step

2) How to get it in a reverse order?

Change the final order by like ORDER BY sequence desc, ordinal , lid

like image 197
Akhil Avatar answered Nov 14 '22 23:11

Akhil