2010-02-18 64 views
3

我有一個包含類似值的字段:SQL分裂樣選擇

A12345 
AB456 
1234 
AA 45 

反正有兩個單獨的列,數字和字母選擇這些。

在此先感謝

+1

您的第五個示例行中的空格是否與字母一起包含或被丟棄? – 2010-02-18 14:46:07

+0

請包括您正在使用的數據庫的品牌,因爲SQL功能因引擎而異。例如,有些允許正則表達式,有些則不允許。 – 2010-02-18 15:03:16

回答

0

如果您使用的是支持,你可以寫上解析出來,並返回唯一值的表用戶定義函數的SQL引擎。如果你打算做很多事情,你可能會更好地將它們存儲爲單獨的字段,以便您可以使用DML而不是自定義代碼來操作它們。

0
create table tbl(data varchar(200)) 

insert into tbl(data) 
select 'A12345' data union all 
select 'AB456' union all 
select '1234' union all 
select 'AA 45' 

------------- 

select LEFT(data, PATINDEX('%[0-9]%', data)-1) as Letters, 
     CAST(SUBSTRING(data, PATINDEX('%[0-9]%', data), 10000) AS INT) as Numbers 
from tbl 
+0

我可以被認爲是sql中的新手...你對這個解決方案有什麼看法?謝謝。 (REPLACE(REPLACE('ABC34567','1',''),'2',''),'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' 3' , ''), '4', ''), '5', ''), '6', ''), '7', ''), '8', ''), '9' ('ABC34567','''),'0',''), SUBSTRING('ABC34567',LEN(REPLACE(REPLACE(REPLACE('REPLACE',REPLACE ''), '2', ''), '3', ''), '4', ''), '5', ''), '6', ''), '7', '' ), '8', ''), '9', ''), '0', ''))+ 1,LEN( 'ABC34567')) – dfm 2010-02-18 20:19:55

3

如果沒有正則表達式的話,或許這樣的事情將削減它。

SQL> with t as (select 'A12345' as str from dual 
    2  union all 
    3  select 'AB456' as str from dual 
    4  union all 
    5  select '1234' as str from dual 
    6  union all 
    7  select 'AA 45' as str from dual) 
    8 select str 
    9   , replace(translate(str, '' 
10        , '   '), ' ', null) as AAA 
11   , replace(translate(str, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 
12        , '       '), ' ', null) as NNN 
13 from t 
14/

STR AAA NNN 
------ ------ ------ 
A12345 A  12345 
AB456 AB  456 
1234   1234 
AA 45 AA  45 

SQL> 

translate()函數轉換的數字(或字母)爲空格,那麼replace()變成空格成空值。