2017-05-09 71 views
0

說明我有了一個表:ORDER BY在Sybase

nb | label 
60 | from 2 and less 
25 | from 3 to 16 
15 | from 17 to 100 

我努力讓我用查詢來獲取降序:

select * from table order by label desc; 

但我沒有得到正確的訂單,而我有以下幾種:

[ { nb: 25, label: 'from 3 to 16' }, 
    { nb: 60, label: 'from 2 and less' }, 
    { nb: 15, label: 'from 17 to 100' } ] 

它認爲17是1嗎?我怎樣才能得到正確的訂單?

謝謝你的幫助

+0

提取數字部分並將其轉換爲整型數據類型。 – jarlh

+0

如果你可以把2和3的0面前,那麼它會按你想要的方式排序。字符串根據他們遇到的第一個字符進行排序,所以3> 2> 1它不會看到它後面的7。 '來自空間匹配'的第一個方差是3,2,1,並且這個字符串正確排序。添加0或將數字轉換爲數字值。 – xQbert

回答

1

這是一種痛苦。最簡單的是,如果您有另一列具有相同的順序。不過,假設第二個字是不與0開始和第一個字是「從」的整數:

order by patindex('%[0-9] %', label) desc, 
     left(label, patindex('%[0-9] %', label)) desc 

這基本上找到的第一個數字的長度,並使用該在order by第一密鑰。然後它按第一個數字排序。

+0

謝謝你的回答,這個答案給出了升序,但是當我把: order by patindex('%[0-9]%',label), left(label,patindex('%[0-9 ]%',label))desc它不起作用 – Jean

+0

@Jean。 。 。這兩個鍵都需要'desc'。 –

1

快速修復,只是將其更改爲:

     ...from 03 to 16' }, 
     { nb: 60, label: 'from 02 and less' }, 
     { nb: 15, label: 'from 17 to 100' } ] 

或額外的空間,而不是零:

     ...from 3 to 16' }, 
     { nb: 60, label: 'from 2 and less' }, 
     { nb: 15, label: 'from 17 to 100' } ] 

都應該你想要的方式排序。