我有这样的数据:
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_之后只排序第一个数字,我不知道如何得到这个数字。
我尝试过使用susbsting(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
我该怎么做?
答案 0 :(得分:1)
SELECT SUBSTRING(CODE_VD,3, CHARINDEX('_',CODE_VD, 3)-3)
答案 1 :(得分: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
答案 2 :(得分: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