How do I sort a VARCHAR column in SQL server that contains numbers?

后端 未结 11 1964
慢半拍i
慢半拍i 2020-11-27 14:08

I have a VARCHAR column in a SQL Server 2000 database that can contain either letters or numbers. It depends on how the application is configured o

相关标签:
11条回答
  • 2020-11-27 14:13

    I solved it in a very simple way writing this in the "order" part

    ORDER BY (
    sr.codice +0
    )
    ASC
    

    This seems to work very well, in fact I had the following sorting:

    16079   Customer X 
    016082  Customer Y
    16413   Customer Z
    

    So the 0 in front of 16082 is considered correctly.

    0 讨论(0)
  • 2020-11-27 14:14
    SELECT *, CONVERT(int, your_column) AS your_column_int
    FROM your_table
    ORDER BY your_column_int
    

    OR

    SELECT *, CAST(your_column AS int) AS your_column_int
    FROM your_table
    ORDER BY your_column_int
    

    Both are fairly portable I think.

    0 讨论(0)
  • 2020-11-27 14:14
    SELECT FIELD FROM TABLE
    ORDER BY 
      isnumeric(FIELD) desc, 
      CASE ISNUMERIC(test) 
        WHEN 1 THEN CAST(CAST(test AS MONEY) AS INT)
        ELSE NULL 
      END,
      FIELD
    

    As per this link you need to cast to MONEY then INT to avoid ordering '$' as a number.

    0 讨论(0)
  • 2020-11-27 14:19

    There are a few possible ways to do this.

    One would be

    SELECT
     ...
    ORDER BY
      CASE 
        WHEN ISNUMERIC(value) = 1 THEN CONVERT(INT, value) 
        ELSE 9999999 -- or something huge
      END,
      value
    

    the first part of the ORDER BY converts everything to an int (with a huge value for non-numerics, to sort last) then the last part takes care of alphabetics.

    Note that the performance of this query is probably at least moderately ghastly on large amounts of data.

    0 讨论(0)
  • 2020-11-27 14:19

    This seems to work:

    select your_column  
    from your_table  
    order by   
    case when isnumeric(your_column) = 1 then your_column else 999999999 end,  
    your_column   
    
    0 讨论(0)
  • 2020-11-27 14:21

    This query is helpful for you. In this query, a column has data type varchar is arranged by good order.For example- In this column data are:- G1,G34,G10,G3. So, after running this query, you see the results: - G1,G10,G3,G34.

    SELECT *,
           (CASE WHEN ISNUMERIC(column_name) = 1 THEN 0 ELSE 1 END) IsNum
    FROM table_name 
    ORDER BY IsNum, LEN(column_name), column_name;
    
    0 讨论(0)
提交回复
热议问题