2014-07-03 103 views
0

子排序SQL我擁有的數據是這樣的:與字符串

CODE_VD 

N_10_19_xxx 
N_0_3_xxx 
N_121_131_xxx 
N_100_120_xxx 
N_80_90_xxx 
N_20_29_xxx 

,你可以看到我需要梳理剛剛N_後的第一個數字,我不知道我怎樣才能得到這個數字。

我已經試過了(CODE_VD,2,3),但並不完全符合我的預期。

我想這一點:

CODE_VD 

N_0_3_xxx 
N_10_19_xxx 
N_20_29_xxx 
N_80_90_xxx 
N_100_120_xxx 
N_121_131_xxx 

我該怎麼辦呢?

回答

1
DECLARE @MyTable TABLE 
(
    CODE_VD VARCHAR(20) 
) 

INSERT INTO @MyTable 
(CODE_VD) 
VALUES 
('N_10_19_xxx'), 
('N_0_3_xxx'), 
('N_121_131_xxx'), 
('N_100_120_xxx'), 
('N_80_90_xxx'), 
('N_20_29_xxx'); 

SELECT * FROM 
(
    SELECT 
     *, 
     CONVERT(INT, 
     SUBSTRING(mt.CODE_VD, 
      3, 
      CHARINDEX('_', mt.CODE_VD, 3) - 3)) ConvCol 
    FROM @MyTable mt 
) mt 
ORDER BY mt.ConvCol 

我轉換爲int,以獲得某種正常工作,因爲100> 20

1
SELECT SUBSTRING(CODE_VD,3, CHARINDEX('_',CODE_VD, 3)-3) 
0
declare @t Table (CODE_VD VARCHAR(MAX)) 
INSERT INTO @t (CODE_VD)VALUES ('N_10_19_xxx') 
INSERT INTO @t (CODE_VD)VALUES ('N_0_3_xxx') 
INSERT INTO @t (CODE_VD)VALUES ('N_121_131_xxx') 
INSERT INTO @t (CODE_VD)VALUES ('N_100_120_xxx') 


;WITH 
    sorted 
AS 
(
    SELECT 
    *, 
    ROW_NUMBER() OVER (PARTITION BY SUBSTRING(CODE_VD,3, CHARINDEX('_',CODE_VD, 3)-3) ORDER BY CODE_VD) AS sequence_id 
    FROM 
    @t 
) 
SELECT 
    CODE_VD 
FROM 
    sorted 
WHERE 
    sequence_id = 1