varchar的一个字段:列值为101,104,201,1010,301-1。order by 如何排序?

558047 2006-11-02 02:11:34
field1 varchar(5)
101
1010
104
301-1
201
302-1
....
如何Order by 成如下这样
101
104
201
1010
301-1
302-2
就是不带‘-’横线的让它们以数值大小排序,带横线的排在它们后边
...全文
382 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
gc_ding 2006-11-03
  • 打赏
  • 举报
回复
为啥这样会出错:
ORDER BY 子句中的位置号 100000 超过了选择列表中项数目。

declare @t table(field1 varchar(5))
insert @t

select '301-1' union all
select '302-1'

select *
from @t
order by 100000

这个100000不是对应排那些非数字的记录么?(not like '%[^0-9]%' 排数字)
558047 2006-11-03
  • 打赏
  • 举报
回复
高!
dulei115 2006-11-03
  • 打赏
  • 举报
回复
改一下:
declare @t table(field1 varchar(5))
insert @t
select '101' union all
select '1010' union all
select '104' union all
select '301-1' union all
select '201' union all
select '302-1'

select *
from @t
order by case when field1 not like '%[^0-9]%' then cast(field1 as int) else 100000 end --因为你字段的长度为5,纯数字的转换后肯定不会大于或等于100000

/*
field1
101
104
201
1010
301-1
302-1
*/
allright_flash 2006-11-03
  • 打赏
  • 举报
回复
dulei115 2006-11-03
  • 打赏
  • 举报
回复
declare @t table(field1 varchar(5))
insert @t
select '101' union all
select '1010' union all
select '104' union all
select '301-1' union all
select '201' union all
select '302-1'


select *
from @t
order by case when field1 not like '%[^0-9]%' then cast(field1 as int) else 99999999 end
seahi 2006-11-03
  • 打赏
  • 举报
回复
倒,这个就难搞了。
558047 2006-11-02
  • 打赏
  • 举报
回复
让纯数字的以数值大小排序,不是纯数字的随便排,不排在那些数字面前就行
marco08 2006-11-02
  • 打赏
  • 举报
回复
那就沒辦法了
558047 2006-11-02
  • 打赏
  • 举报
回复
对了
这列的值还有可能是1~50A等这样的字符
hellowork 2006-11-02
  • 打赏
  • 举报
回复
declare @t table(field1 varchar(5))
insert @t
select '101' union all
select '1010' union all
select '104' union all
select '301-1' union all
select '201' union all
select '302-1'

select * from @t order by cast(replace(field1,'-','') as bigint)

/*结果
101
104
201
1010
301-1
302-1
*/

27,581

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧