简体   繁体   中英

How to sort by number in SQL Server?

I have a table with a column stored as string, but it is really a number like this:

17 - Doe
2 - Mike
3 - James

I need to sort them and create a output like this:

2 - Mike
3 - James
17 - Doe

How to write the SQL? Thanks in advance!

try this:

DECLARE @Yourtable table (data varchar(50))
insert into @Yourtable values ('17 - Doe')
insert into @Yourtable values ('2 - Mike')
insert into @Yourtable values ('3 - James')

SELECT * FROM @Yourtable order by CONVERT(int,left(data, charindex('-', data)-1))

You shouldn't store your data this way, add a new int column to this table and run this to fix your table :

DECLARE @Yourtable table (data varchar(50), newINT int)
insert into @Yourtable values ('17 - Doe',null)
insert into @Yourtable values ('2 - Mike',null)
insert into @Yourtable values ('3 - James',null)

UPDATE @Yourtable
    SET newINT=CONVERT(int,left(data, charindex('-', data)-1))
        ,data=RIGHT(data, LEN(data)-charindex('-', data)-1)

you can add an index to the new int column if you need to join or select by it. Now you can do a regular ORDER BY on it.

Two big assumptions - if the format is always as described then you can pull out the integer in your order by. Dont have sql server to test but something like this

order by cast(left(yourcol, charindex('-', yourcol) as integer))

Forgive me If I've missed out a point, but I feel this is pretty simple and straightforward. Below is the query i used to get your desired result. It will work for any number preceding a name..

select col from *table_name* order by convert(int,substring(id,0,charindex('-',id)));

Kindly point out someone if I've missed something...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM