2012-10-09 169 views

回答

2

你可以試試這個可怕的事情。這證明,這將是更好地將這些值存儲在兩個領域...

ORDER BY 
CAST(SUBSTRING(Number, 0, 
    case when patindex('%[a-zA-Z]%', Number) = 0 
    then len(Number)+1 
    else patindex('%[a-zA-Z]%', Number) 
    end) 
as INT), 
Number 

SqlFiddle

+0

這是不正確的。它會把'20'放在'14AA'之前。 – RichardTheKiwi

+0

@RichardTheKiwi你是對的,編輯過。 –

+0

仍然不起作用 –

3

對於PostgreSQL和SQL Server中,我假設你的列中只包含字母數字。

MySQL的SQLite的&

ORDER BY StrangeCol*1, StrangeCol 

PostgreSQL的

order by cast(trim(both 'abcdefghijklmnopqrstuvwxyz' 
        from lower(StrangeCol)) as int), StrangeCol 

SQL服務器

order by 0+stuff(StrangeCol+'a',patindex('%[a-Z]%',StrangeCol+'a'),999,''), StrangeCol 

甲骨文

order by 0+regexp_replace(StrangeCol, '[^[:digit:]]') ,StrangeCol 
+0

我不能說所有的例子,但SQL服務器部分失敗 –

+0

@ t-cl你有什麼定義'失敗'? http://sqlfiddle.com/#!3/d127c/3/0 – RichardTheKiwi

+0

這真的很奇怪,每當我在2008年運行你的腳本時都會失敗。'轉換失敗時將varchar值'14AA'轉換爲數據類型int 「。 –

0

你應該澄清你的訂單類型。例如在14AA中,你說第一部分解釋爲數字,第二部分解釋爲字母!

如果你想混合他們,我建議使用HEX基地。

2

試試這個:

create table tblNum(id varchar(10)) 

insert into tblNum 
values('1'),('10'),('11'),('14'),('14A'),('14AA'),('19'),('2'),('20'),('21') 

select id from tblNum order by 
CASE WHEN PATINDEX('%[a-zA-Z]%',id) > 0 then cast(left(id,(PATINDEX('%[a-zA-Z]%',id)-1)) as int) else cast(id as int) end 
+0

@Downvoter - 給評論簡單downvoting將不是一個好的做法 – AnandPhadke

+0

我appologize我的數據庫是有趣的。出於某種原因,它給出了錯誤的結果。與@RichardTheKiwi一樣的錯誤 –