2010-10-06 85 views
1

SQL排序數字,然後在這個例子中按字母順序

10-20 
20-40 
50-60 

v 
k 
r 
a 

12 month 
1 month 

我怎麼可以在這個進行排序是:

10-20 
20-40 
50-60 

a 
k 
r 
v 

1 month 
12 month 

我使用ABS(值),但在字母大小寫不工作

+0

是1個例或3個例子? – 2010-10-06 21:55:36

+0

它是1個例子 – cosy 2010-10-06 21:56:22

+1

[自然排序在MySQL](http://stackoverflow.com/questions/153633/natural-sort-in-mysql)可能的重複 – jball 2010-10-06 21:57:27

回答

1

好的,感謝評論者,現在是一個工作版本。這個排序了兩起案件中的ORDER BY子句:

select * 
from (
     select '10-20' as col1 
     union all select '20-40' 
     union all select '50-60' 
     union all select 'v' 
     union all select 'k' 
     union all select 'r' 
     union all select 'a' 
     union all select '12 month' 
     union all select '1 month' 
     ) s1 
order by 
     case 
      when col1 rlike '[0-9][0-9]-[0-9][0-9]' then 1 
      when col1 rlike '[0-9]+ month' then 3 
      else 2 
     end 
,  case 
      when col1 rlike '[0-9][0-9]-[0-9][0-9]' then cast(col1 as decimal) 
      when col1 rlike '[0-9]+ month' then cast(col1 as decimal) 
      else col1 
     end 

第一種情況提出類別依次爲:00-00先,然後其他的東西,並在最後的幾個月。如果可能,第二種情況將列轉換爲十進制。

+0

在「10」之後放置「2」 – nickf 2010-10-06 21:56:49

2

如果你能逃脫做了一些用PHP處理,你可以使用natsort

Standard sorting 
Array 
(
    [3] => img1.png 
    [1] => img10.png 
    [0] => img12.png 
    [2] => img2.png 
) 

Natural order sorting 
Array 
(
    [3] => img1.png 
    [2] => img2.png 
    [1] => img10.png 
    [0] => img12.png 
) 

否則,有它要求同一件事上SO另一個問題:Natural Sort in MySQL

相關問題