SQL for ordering by number - 1,2,3,4 etc instead of 1,10,11,12

前端 未结 8 1870
清歌不尽
清歌不尽 2020-11-30 19:13

I’m attempting to order by a number column in my database which has values 1-999

When I use

ORDER_BY registration_no ASC

I get….

相关标签:
8条回答
  • 2020-11-30 20:03

    I assume your column type is STRING (CHAR, VARCHAR, etc) and sorting procedure is sorting it as a string. What you need to do is to convert value into numeric value. How to do it will depend on SQL system you use.

    0 讨论(0)
  • 2020-11-30 20:08

    I prefer doing a "PAD" to the data. MySql calls it LPAD, but you can work your way around to doing the same thing in SQL Server.

    ORDER BY  REPLACE(STR(ColName, 3), SPACE(1), '0') 
    

    This formula will provide leading zeroes based on the Column's length of 3. This functionality is very useful in other situations outside of ORDER BY, so that is why I wanted to provide this option.

    Results: 1 becomes 001, and 10 becomes 010, while 100 remains the same.

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