开发者

how to sort varchar numeric columns by DESC or ASC?

I write ...

ORDER BY column ASC

but my column is VARCHAR and 开发者_开发知识库it sorts wrong like 1, 10, 2, instead of 1, 2, 10.

How can I do it to sort like 1, 2, 10?


order by 
   cast(column as float)

Notes:

  • Assumed you only have numbers in the columns. No "fish" or "bicycle"
  • empty strings CAST to zero

Edit: For MySQL. You can not cast to float

order by 
   cast(column as decimal(38,10))


You can cast to int...

order by cast(column as int)

DEMO

DECLARE @q as table(
name varchar(50),
columnn varchar(10)

)
insert into @q
VALUES('one','1'),('one','10'),('one','20'),('one','3'),('one','2'),('one','20')


select * from @q order by cast  (columnn as int) desc

prints

-------------------------------------------------- ----------
one                                                20
one                                                20
one                                                10
one                                                3
one                                                2
one                                                1

So, Daniel, yes, it works :)

UPDATE:

order by cast(column as decimal(20,6))

Will cast the column values to decimal numbers with 20 digits max and 6 decimal places. Adjust it to your actual requirements.


Try this:

order by CAST(column as UNSIGNED)


i used this way multiply it with one the query is :

ORDER BY columnname * 1 ASC

Example: Table user have value with column value [varchar(20)]. Then you can query it:

SELECT * FROM user ORDER BY value * 1

After we multiply it MySQL will treat it like a number but this way is not recommended for a heavy load.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜