简体   繁体   中英

How to sort sql server result based on first smallest to largest, Numeric followed by Alpha

SELECT CASE WHEN LTRIM(BINNUMBER)='999999' THEN 'NO BIN' ELSE BINNUMBER END AS BINNUMBER,
                                      --SELECT BINNUMBER,
                                      SUBCLASS,
                                      STYLE_DESCRIPTION,
                                      style_code,
                                      color_code,
                                      size_code,
                                      QUANTITY_SOLD,
                                      SOH,
                                      CURRENT_PRICE     
                                      FROM #Final_By_Selection_withMinBin
                                      --WHERE BINNUMBER NOT BETWEEN '1' AND '999999'  || NOT BETWEEN @intFrom_BinNo AND @intTo_BinNo
                                      WHERE MIN_BINNUMBER NOT BETWEEN @intFrom_BinNo AND @intTo_BinNo
                                      ORDER BY

                                     --LEFT(size_master_id,PATINDEX('%[0-9]%',size_master_id)-1), -- alphabetical sort
                                     --CONVERT(VARCHAR,SUBSTRING(size_master_id,PATINDEX('%[0-9]%',size_master_id),LEN(size_master_id))) -- numerical sort

                                        substring(size_master_id, 0,patindex('%[0-9]%',size_master_id))+right ('00000' + substring(size_master_id,
                                        patindex('%[0-9]%',size_master_id) , len(size_master_id)),5)
                                                                END

Assuming your column to be in the format of 'NNNNAAA' (N-numeric, A-alphabets), you can use

ORDER BY 
CAST(CASE WHEN PATINDEX('%[a-zA-Z]%', description) > 0 THEN 0 ELSE -1 END AS INT),

CAST(CASE WHEN substring(description,PATINDEX('%[0-9]%', description),ISNULL( NULLIF( PATINDEX('%[a-zA-Z]%', description) - 1, -1 ),LEN(description) )) = '' THEN 2147483647
          ELSE substring(description,PATINDEX('%[0-9]%', description),ISNULL( NULLIF( PATINDEX('%[a-zA-Z]%', description) - 1, -1 ),LEN(description) )) 
          END AS INT),

substring(description,PATINDEX('%[a-zA-Z]%', description),LEN(description) - PATINDEX('%[a-zA-Z]%', description) + 1

To explain:

PATINDEX gets me the first alpha's index / first numeric's index in that string. So, first I am sorting the output by whether a numeric part is present or not and then sorting the same by alpha part. Hope this helps you.

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