[英]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? 如何编写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 : 您不应该以这种方式存储数据,向此表添加新的int列并运行此列来修复表 :
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. 如果需要加入或选择索引,可以在新的int列中添加索引。 Now you can do a regular ORDER BY on it.
现在你可以对它进行常规的ORDER BY。
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
没有sql server来测试但是这样的东西
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... 如果我错过了什么,请指出某人......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.