简体   繁体   中英

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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