如何根据从小到大的数字排序sql server结果

时间:2019-04-05 07:18:51

标签: sql sql-server

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

1 个答案:

答案 0 :(得分:0)

假设您的列的格式为“ 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

说明:

PATINDEX为我提供了该字符串中的第一个字母索引/第一个数字索引。因此,首先我要根据是否存在数字部分对输出进行排序,然后再按alpha部分对输出进行排序。希望对您有帮助。