简体   繁体   English

如何根据第一个最小到最大,数字后跟Alpha对sql server结果进行排序

[英]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假设您的列采用“NNNNAAA”(N 数字、A 字母)格式,您可以使用

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. PATINDEX 为我获取该字符串中的第一个字母索引/第一个数字索引。 So, first I am sorting the output by whether a numeric part is present or not and then sorting the same by alpha part.因此,首先我按数字部分是否存在对输出进行排序,然后按 alpha 部分对输出进行排序。 Hope this helps you.希望这对你有帮助。

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

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