Conditional Order By

岁酱吖の 提交于 2019-12-21 20:47:11

问题


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
...


回答1:


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


来源:https://stackoverflow.com/questions/15349677/conditional-order-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!