如何对 SQL 中同时包含数字和字母数字值的行进行升序排序?
How to sort rows in SQL that contain both numeric & alphanumeric values in ascending order?
我的 SQL 查询返回了以下行 - 有人可以帮忙提供通用排序代码以按升序对值进行排序吗?
另请注意,我的行将被动态返回,并且不会始终包含与我在上面的问题中发布的相同的字符串。它将是 alphabets/integers 的混合。下面只是返回示例行的示例 - 需要通用 formulae/sql 方法而不是硬编码方法..谢谢
('High_Speed'),
('M1 Speed'),
('M13 Speed'),
('M14 Speed'),
('M2 Speed'),
('M3 Speed'),
('Medium_Speed'),
('Test1 zone1 High_Speed'),
('Test1 zone11 High_Speed'),
('Test1 zone2 High_Speed'),
('Test1 zone21 High_Speed'),
('Zone206 Speed')
预期排序-
('High_Speed'),
('M1 Speed'),
('M2 Speed'),
('M3 Speed'),
('M13 Speed'),
('M14 Speed'),
('Medium_Speed'),
('Test1 zone1 High_Speed'),
('Test1 zone2 High_Speed'),
('Test1 zone11 High_Speed'),
('Test1 zone21 High_Speed'),
('Zone206 Speed')
试试这个:
select t_col from (
select t_col
, LEFT(SUBSTRING(t_col, PATINDEX('%[a-z]%', t_col), LEN(t_col))
, PATINDEX('%[^a-z]%', SUBSTRING(t_col, PATINDEX('%[a-z]%', t_col), LEN(t_col)))-1) col_col
, convert(int, LEFT(SUBSTRING(t_col, PATINDEX('%[0-9]%', t_col), LEN(t_col))
, PATINDEX('%[^0-9]%', SUBSTRING(t_col, PATINDEX('%[0-9]%', t_col), LEN(t_col)))-1)) as ord
from test) T1
order by col_col asc, ord asc, t_col asc;
我的 SQL 查询返回了以下行 - 有人可以帮忙提供通用排序代码以按升序对值进行排序吗?
另请注意,我的行将被动态返回,并且不会始终包含与我在上面的问题中发布的相同的字符串。它将是 alphabets/integers 的混合。下面只是返回示例行的示例 - 需要通用 formulae/sql 方法而不是硬编码方法..谢谢
('High_Speed'),
('M1 Speed'),
('M13 Speed'),
('M14 Speed'),
('M2 Speed'),
('M3 Speed'),
('Medium_Speed'),
('Test1 zone1 High_Speed'),
('Test1 zone11 High_Speed'),
('Test1 zone2 High_Speed'),
('Test1 zone21 High_Speed'),
('Zone206 Speed')
预期排序-
('High_Speed'),
('M1 Speed'),
('M2 Speed'),
('M3 Speed'),
('M13 Speed'),
('M14 Speed'),
('Medium_Speed'),
('Test1 zone1 High_Speed'),
('Test1 zone2 High_Speed'),
('Test1 zone11 High_Speed'),
('Test1 zone21 High_Speed'),
('Zone206 Speed')
试试这个:
select t_col from (
select t_col
, LEFT(SUBSTRING(t_col, PATINDEX('%[a-z]%', t_col), LEN(t_col))
, PATINDEX('%[^a-z]%', SUBSTRING(t_col, PATINDEX('%[a-z]%', t_col), LEN(t_col)))-1) col_col
, convert(int, LEFT(SUBSTRING(t_col, PATINDEX('%[0-9]%', t_col), LEN(t_col))
, PATINDEX('%[^0-9]%', SUBSTRING(t_col, PATINDEX('%[0-9]%', t_col), LEN(t_col)))-1)) as ord
from test) T1
order by col_col asc, ord asc, t_col asc;