答案 0 :(得分:4)
您可以尝试以下查询。
;WITH cte
AS (SELECT title,
Cast(Substring(title, Charindex('(', title) + 1,
Charindex(')', title) -
Charindex('(', title) - 1)
AS INT) AS OC
FROM yourtable)
SELECT *
FROM cte
ORDER BY oc
在上述查询中,括号之间的数字被提取并转换为INT
进行排序。
答案 1 :(得分:2)
使用SUBSTRING()
和PATINDEX()
,可以进行以下排序:
DECLARE @TestTable TABLE (TestVal VARCHAR (20));
INSERT INTO @TestTable (TestVal) VALUES ('Test (1)'), ('Test (10)'), ('Test (2)');
SELECT TestVal
FROM @TestTable
ORDER BY CAST(SUBSTRING(TestVal, PATINDEX('%[0-9]%', TestVal), LEN(TestVal) - PATINDEX('%[0-9]%', TestVal)) AS INT),
LEFT(TestVal, PATINDEX('%[0-9]%', TestVal) - 2)
输出:
TestVal
---------
Test (1)
Test (2)
Test (10)
答案 2 :(得分:1)
您也可以尝试以下方法:
declare @t table (title varchar(50))
insert into @t values ('InterSciences Competition (1)')
insert into @t values ('InterSciences Competition (10)')
insert into @t values ('InterSciences Competition (2)')
select * from @t
order by cast(replace(substring(title,CHARINDEX('(',title)+1,CHARINDEX(')',title)),')','') as INT)