简体   繁体   English

如何按升序对包含数字和字母数字值的 SQL 中的行进行排序?

[英]How to sort rows in SQL that contain both numeric & alphanumeric values in ascending order?

I have the following rows returned from my SQL query- can someone please help with a generic sorting code to sort the values in ascending order?我的 SQL 查询返回了以下行 - 有人可以帮忙使用通用排序代码以升序对值进行排序吗?

Also please note that my rows will be dynamically returned and will not always contain the same string as posted in my question above.另请注意,我的行将动态返回,并且不会始终包含与上述问题中发布的字符串相同的字符串。 It will be a mix of alphabets/integers.它将是字母/整数的混合。 Below is just an example of a sample rows returned- need a generic formulae/sql approach and NOT a hard coding approach..thanks下面只是返回的示例行的示例 - 需要通用公式/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')

expected sorting-预期排序-

('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')

Try this:尝试这个:

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;

Here is a demo 这是一个演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM