SQL Server 2008 - order by strings with number numerically

前端 未结 5 1431
感动是毒
感动是毒 2020-12-01 16:06

I have following values in my table:

ABC
ABC1
ABC2
ABC3 and so on...

ABC11
ABC12
ABC13 and so on..

ABC20
ABC21
ABC22 and so on..

So basic

相关标签:
5条回答
  • 2020-12-01 16:51

    You could adapt the function RemoveNonAlphaCharacters in this answer to filter out everything except numbers, and then use an ORDER BY using that function.

    0 讨论(0)
  • 2020-12-01 16:52

    In order by statement, prepend enough zeros with when value contains any number in it to make all alphanumerica value same length

    SELECT ColName
    FROM TableName
    ORDER BY 
     CASE WHEN ColName like '%[0-9]%' 
     THEN Replicate('0', 100 - Len(ColName)) + ColName
     ELSE ColName  END
    
    0 讨论(0)
  • 2020-12-01 16:58

    You could remove the first three characters and cast the rest to int

    SELECT Value,
           Num=CAST(RIGHT(Value, LEN(Value) - 3) AS int)
    FROM dbo.TableName
    ORDER BY Num
    

    Demo

    0 讨论(0)
  • 2020-12-01 17:03

    (based on answers from @shenhengbin and @EchO to this question)

    The following is what I call a "clean hack". Assuming you are ordering on column Col1:

    ORDER BY LEN(Col1), Col1
    

    It is a hack, although I'd personally feel proud using it.

    0 讨论(0)
  • 2020-12-01 17:06

    You can do it using PATINDEX() function like below :

    select * from Test 
    order by CAST(SUBSTRING(Name + '0', PATINDEX('%[0-9]%', Name + '0'), LEN(Name + '0')) AS INT)
    

    SQL Fiddle Demo

    If you have numbers in middle of the string then you need to create small user defined function to get number from string and sort data based on that number like below :

    CREATE FUNCTION dbo.fnGetNumberFromString (@strInput VARCHAR(255)) 
    RETURNS VARCHAR(255) 
    AS 
    BEGIN 
        DECLARE @intNumber int 
        SET @intNumber = PATINDEX('%[^0-9]%', @strInput)
    
        WHILE @intNumber > 0
        BEGIN 
            SET @strInput = STUFF(@strInput, @intNumber, 1, '')
            SET @intNumber = PATINDEX('%[^0-9]%', @strInput)
        END 
    
        RETURN ISNULL(@strInput,0) 
    END 
    GO
    

    You can sort data by :

    select Name from Test order by dbo.fnGetNumberFromString(Name), Name
    
    0 讨论(0)
提交回复
热议问题