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

前端 未结 8 2308
清歌不尽
清歌不尽 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: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.

提交回复
热议问题