简体   繁体   中英

Alphanumeric and Numeric sorting in SQL Server

I need to apply sorting on Alphanumeric and Numeric sorting.

Example:

319,
519, 
620, 
1154, 
1195, 
319lov,
319, 
620lov

I need result like:

319,
319,
319lov,
519, 
620, 
620lov,
1154, 
1195, 

I have applied following code to sort:

SELECT Name 
FROM TableName
ORDER BY CAST(CASE
                 WHEN Name LIKE '[0-9][0-9][0-9][0-9]%' THEN LEFT(Name ,4)
                 WHEN Name LIKE '[0-9][0-9][0-9]%' THEN LEFT(Name ,3)
                 ELSE NULL 
              END AS INT)

Got result like:

319,
319lov,
319,
519, 
620,
620lov, 
1154, 
1195,  
SELECT name FROM t 
ORDER BY CONVERT(INT, LEFT(name, PATINDEX('%[^0-9]%', name+'z')-1)),name;

You order by all the numbers up to the first non number,the letter is in there to treat all strings the same.

FIDDLE

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