Sort string as number in sql server

前端 未结 9 1460
不知归路
不知归路 2020-12-20 16:41

I have a column that contains data like this. dashes indicate multi copies of the same invoice and these have to be sorted in ascending order

790711
790109-1         


        
9条回答
  •  醉梦人生
    2020-12-20 17:25

    Try this one -

    Query:

    DECLARE @Invoice TABLE (InvoiceNumber VARCHAR(10))
    INSERT @Invoice 
    VALUES
          ('790711')
        , ('790709-1')
        , ('790709-21')
        , ('790709-11')
        , ('790709-211')
        , ('790709-2')
    
    ;WITH cte AS 
    (
        SELECT 
              InvoiceNumber
            , lenght = LEN(InvoiceNumber)
            , delimeter = CHARINDEX('-', InvoiceNumber)
        FROM @Invoice
    )
    SELECT InvoiceNumber
    FROM cte
    CROSS JOIN (
        SELECT repl = MAX(lenght - delimeter)
        FROM cte
        WHERE delimeter != 0
    ) mx
    ORDER BY 
          SUBSTRING(InvoiceNumber, 1, ISNULL(NULLIF(delimeter - 1, -1), lenght))
        , RIGHT(REPLICATE('0', repl) + SUBSTRING(InvoiceNumber, delimeter + 1, lenght), repl)
    

    Output:

    InvoiceNumber
    -------------
    790709-1
    790709-2
    790709-11
    790709-21
    790709-211
    790711
    

提交回复
热议问题