I have a table with the fields id, group, left, level and createdAt.
Every row belongs to a group. The row with level = 0 is the group “leader”.
I want to sort the table by the leaders’ date, and within each group sort the rows by left. For example, in this table:
Id - Group - Left - Level - CreatedAt
1 1 1 0 00:10
2 1 2 1 00:20
3 2 1 0 00:00
4 1 3 1 00:30
5 2 2 1 00:40
The order should be:
Id - Group - Left - Level - CreatedAt
3 2 1 0 00:00
5 2 2 1 00:40
1 1 1 0 00:10
2 1 2 1 00:20
4 1 3 1 00:30
Because row 3 is the newest group leader, it should be first and followed by all it’s group ordered by left. After that is row 1 which is the second most new leader, followed by it’s group ordered by left.
Etc..
I hope I explained it clear enough.
Thanks!
Essentially, you need to join your table with the leader’s time:
See it on sqlfiddle.
If you can guarantee that there is an unambiguous leader for every group—e.g. because you have defined a
UNIQUEconstraint on(Group, Level), which you cannot have because your example contains two records inGroup = 1withLevel = 1—then you can avoid the grouping operation: