Natural Sorting SQL ORDER BY

余生颓废 提交于 2019-12-30 10:30:03

问题


Can anyone lend me a hand as to what I should append to my ORDER BY statement to sort these values naturally:

1
10
2
22
20405-109
20405-101
20404-100
X
Z
D

Ideally I'd like something along the lines of:

1
2
10
22
20404-100
20405-101
20405-109
D
X
Z

I'm currently using:

ORDER BY t.property, l.unit_number

where the values are l.unit_number

I've tried doing l.unit_number * 1 and l.unit_number + 0 but they haven't worked.

Should I be doing sort of ORDER conditional, such as Case When IsNumeric(l.unit_number)?

Thank you.


回答1:


This will do it:

SELECT value
FROM Table1
ORDER BY value REGEXP '^[A-Za-z]+$'
        ,CAST(value as SIGNED INTEGER)
        ,CAST(REPLACE(value,'-','')AS SIGNED INTEGER)
        ,value

The 4 levels of the ORDER BY:

  1. REGEXP assigns any alpha line a 1 and non-alphas a 0
  2. SIGNED INT Sorts all of the numbers by the portion preceding the dash.
  3. SIGNED INT after removing the dash sorts any of the items with the same value before the dash by the portion after the dash. Potentially could replace number 2, but wouldn't want to treat 90-1 the same as 9-01 should the case arise.
  4. Sorts the letters alphabetically.

Demo: SQL Fiddle



来源:https://stackoverflow.com/questions/17354217/natural-sorting-sql-order-by

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