SQL query ordering in custom order

醉酒当歌 提交于 2020-01-13 18:39:07

问题


I have a custom ordering need like this:

normal ordering  |  custom ordering 
      1          |        7
      2          |        6
      3          |        5
      4          |        4
      5          |        3
      6          |        2
      7          |        8
      .          |        .
      .          |        .
      .          |        .
      .          |        .
      .          |        N
      N          |        1

I have thought about using UNION to combine 3 different select queries with the help of ORDER BY and LIMIT. However, I can not do that because UNION have to be used before ORDER BY and LIMIT.

How can I make a selection (or selections) to achieve the custom ordering above?

Another workaround might help is just make the 1st record returned in this select query the last record, but how?


回答1:


Try this:

SELECT x
FROM t1
ORDER BY
    CASE
      WHEN x = 1 THEN 100000001
      WHEN x between 2 and 7 THEN 7 - x
      WHEN x between 8 and ( SELECT max(x) FROM t1 ) - 1 THEN x
      ELSE 100000000 
    END 

100000000 constans must be greather than N.
Here is a simple demo




回答2:


Add a New Table CustomSeq with two columns, Value and Sequence. In that table you can store the values and their custom order. then join to that table and order by it's Sequence column.



来源:https://stackoverflow.com/questions/18212972/sql-query-ordering-in-custom-order

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