ORDER/SORT Column mixed number and number prefixed by char

前端 未结 4 1650
野的像风
野的像风 2021-01-18 12:42

I have a varchar column conteining a code, this code could by only numbers, or number prefixed by a char for example i have a column containing this data :

         


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-18 13:35

    Assuming there's no spaces before the values and there can only be 1-char prefix:

    ORDER BY
      CASE WHEN LEFT(Code, 1) BETWEEN '0' AND '9' THEN ' ' ELSE LEFT(Code, 1) END,
      CAST(STUFF(Code, 1, CASE WHEN LEFT(Code, 1) BETWEEN '0' AND '9' THEN 0 ELSE 1 END, '') AS int)
    

    Alternatively, the second criterion could be rewritten like this:

      CAST(STUFF(Code, 1, PATINDEX('[^0-9]%', Code), '') AS int)
    

    PATINDEX('[^0-9]%', Code) returns 1 if it finds a non-numeric character at the beginning of Code, and 0 otherwise. As a result, STUFF either removes 1 character, or none, i.e. same as previously.

提交回复
热议问题