varchar范围的order子句

时间:2018-06-04 19:46:31

标签: sql database

我目前在db中有一个列,其中几个范围存储为varchar,例如:

0-499
1000-1199
500-999

如何订购以下范围:

0-499
500-999
1000-1199

提前致谢

5 个答案:

答案 0 :(得分:3)

如果你想变得棘手,你可以这样做:

order by cast(replace(col, '-', '.') as decimal(30, 15))

这用小数点替换连字符,转换为数值,并使用它进行排序。这应该适用于任何数据库。

这并不完美,因为它并没有按照正确的第二个数字顺序排序。但是第一个数字需要完全匹配(出于某种原因,这似乎不太可能基于您的样本数据)。

答案 1 :(得分:0)

按连字符前的字符排序,转换为整数。

答案 2 :(得分:0)

您可以将"FullRow"子句与const numDataPoints = [{ x0: {x: 807, y: 625}, x1: {x: 15, y: 20}, x2: {x: 5, y: 20} }, { x0: {x: 11, y: 6}, x1: {x: 16, y: 21}, x2: {x:7, y: 22} }]; // In case you need them sorted and in the original nesting: console.log( numDataPoints .map(d => Object.keys(d).sort().map(k => [d[k].x, d[k].y])) ); // In case you need them sorted and flattened: console.log( numDataPoints .map(d => Object.keys(d).sort().map(k => [d[k].x, d[k].y])) .reduce((a,v) => { v.forEach(value => a.push(value)); return a; }, []) ); // In case you don't need them sorted and in the original nesting: console.log( numDataPoints .map(d => Object.keys(d).map(k => [d[k].x, d[k].y])) ); // In case you don't need them sorted and flattened: console.log( numDataPoints .map(d => Object.keys(d).map(k => [d[k].x, d[k].y])) .reduce((a,v) => { v.forEach(value => a.push(value)); return a; }, []) );函数一起使用:

order by

但是,前面的left() cluase有int会话,如果你在连字符之前有小数值,那么使用order by cast(left(n, charindex('-', n)-1) as int); 代替

答案 3 :(得分:0)

如果这些是唯一的值:

order by 
case varcharcol when '0-100' then 1
when '500-1000' then 2
when '1000-1199' then 3
end

答案 4 :(得分:0)

create table #temp1(id int,range varchar(50))

insert into #temp1(id,range)
values (1,'0-499'),(2,'1000-1199'),(3,'500-999')

select * from #temp1 order by cast(replace(range, '-', '.') as decimal(30, 15))


id  range
1   0-499
3   500-999
2   1000-1199

select * from #temp1 order by cast (substring(range,0,charindex('-',range)) as int)

id  range
1   0-499
3   500-999
2   1000-1199