user1944934
user1944934

Reputation: 113

Conditional Order By

I have a table where there is a set of routes with a start label and end label. each row has a column "progres" which is the column where to apply the global "order by" clause, and finally a selection column that tells which label types must be ordered (Odd, Even or All). if LabelStart > LabelEnd => order by ASC else by DESC

for example here are the routes path

Routes
ID  RouteID, Progres, LabelStart, LabelEnd  Type 
1   1        5            1          21      O
2   1        10           10          2      E 
4   2        15           2          25      A
5   3        20           1          11      O
6   3        22           4          10      E
7   4        30           5          11      O
8   4        31           2          12      E

and here the points belonging to routes

Points
PoinID  RouteID, Label
1          1        3           
2          1        2
4          1        1 
5          1        8 
6          1        5 
7          1        6 
8          1        9
9          1        21 
10         1        10 
11         1        11 
12         2        1
13         2        2
14         2        12
15         2        3
16         2        25
17         2        14
...  

What I need is a table where all the points are ordered globally by Routes Proges, grouped by Even, Odd or All based on types and finally ordered by ASC if LabelStart > LabelEnd else by DESC. the result shoud be:

ID  RouteID, PointID
1     1        4           
2     1        1
4     1        6 
5     1        8
6     1        11
7     1        9
8     1        10
9     1        5
10    1        7
11    1        2
12    2        13 
13    2        15
...

Upvotes: 3

Views: 5768

Answers (1)

Clodoaldo Neto
Clodoaldo Neto

Reputation: 125214

SQL Fiddle

select 
    row_number() over() id, *
from (
    select
        r.routeid,
        p.pointid,
        label,
        type,
        labelstart,
        labelend
    from
        route r
        inner join
        point p on p.routeid = r.routeid
    where
        r.type = 'E' and p.label % 2 = 0
        or
        r.type = 'O' and p.label % 2 != 0
        or
        r.type = 'A'
    order by
        r.routeid, r.progres, r.id,
        case labelstart < labelend
            when true then label
            else label * - 1
        end
) s

Upvotes: 9

Related Questions