ORDER/SORT Column mixed number and number prefixed by char

前端 未结 4 1649
野的像风
野的像风 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:22
     CASE
        WHEN ISNUMERIC(Col) = 1 THEN '@'
        Else LEFT(Col, 1)
     END
    ,CASE
        WHEN ISNUMERIC(Col) = 1 THEN Convert(int, Col)
        Else Convert(int, RIGHT(Col, LEN(Col) - 1))
     END
    
    0 讨论(0)
  • 2021-01-18 13:26
    SELECT Code FROM Code_List ORDER BY Code, CASE WHEN ISNUMERIC(SUBSTRING(Code,1,1)) = 1 THEN CODE ELSE SUBSTRING(Code,2,LEN(Code)-1) END
    

    Obviously assuming that only the first digit can be alpha

    0 讨论(0)
  • 2021-01-18 13:34

    you might try

    ...ORDER by ('A'+Code)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题