SQL 按字母数字顺序排序
SQL Sort by Alphanumerical Order
所以我在这里查看了几个不同的例子,但是 none 似乎对我有用。
这是我需要排序的示例:
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
...
我是 LEFT
和 RIGHT
的新手,所以我可能做错了什么,所以非常感谢任何指导!
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
所以我在这里查看了几个不同的例子,但是 none 似乎对我有用。
这是我需要排序的示例:
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
...
我是 LEFT
和 RIGHT
的新手,所以我可能做错了什么,所以非常感谢任何指导!
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