SQL按字母数字顺序排序

时间:2015-10-29 14:28:17

标签: sql sql-server alphanumeric

所以我在这里看了几个不同的例子,但是它们似乎都不适合我。

以下是我需要分类的示例:

Alpha #1
Beta #3
Charlie #2
Alpha #2
Charlie #1
Beta #2
Beta #1
Alpha #10

如果排序我想

Alpha #1
Alpha #2
Alpha #10
Beta #1
Beta #2
Beta #3
Charlie #1
Charlie #2

但是,当我使用以下查询时,Alpha #10未遵循所需规则。

ORDER BY 
Case When IsNumeric(LEFT(MachineName,1)) = 1 
     Then CASE When IsNumeric(MachineName) = 1 
               Then Right(Replicate('0',20) + MachineName + '0', 20)
               Else Right(Replicate('0',20) + MachineName, 20) 
          END
     When IsNumeric(LEFT(MachineName,1)) = 0 
     Then Left(MachineName + Replicate('',21), 20)
End

我得到了这个:

Alpha #1
Alpha #10
Alpha #2
...

我是LEFTRIGHT的新手,所以我可能会做错事,所以任何指导都会非常感激!

1 个答案:

答案 0 :(得分:2)

DECLARE @t TABLE(v VARCHAR(100))

INSERT INTO @t VALUES
('Alpha #1'),
('Beta #3'),
('Charlie #2'),
('Alpha #2'),
('Charlie #1'),
('Beta #2'),
('Beta #1'),
('Alpha #10'),
('Alpha #')

SELECT * FROM @t
ORDER BY CASE WHEN PATINDEX('%[0-9]%', v) > 1 THEN SUBSTRING(v, 1, PATINDEX('%[0-9]%', v) - 1) END, 
         CASE WHEN PATINDEX('%[0-9]%', v) > 1 THEN CAST(SUBSTRING(v, PATINDEX('%[0-9]%', v), LEN(v)) AS INT) END

输出:

Alpha #
Alpha #1
Alpha #2
Alpha #10
Beta #1
Beta #2
Beta #3
Charlie #1
Charlie #2