sql排序

lang11zi 2006-02-22 08:47:48
我也问一个排序问题
table1
col1 col2
1 10
2 7
3 8
4 6
5 长10

col2是varchar类型
如何使col2中数字的可以正常排序啊?
...全文
131 13 打赏 收藏 转发到动态 举报
写回复
用AI写文章
13 条回复
切换为时间正序
请发表友善的回复…
发表回复
lang11zi 2006-02-22
  • 打赏
  • 举报
回复
select col1,col2
from table1
order by isnumeric(col2) desc,case when isnumeric(col2)=1 then convert(money,col2) end
就支持小数了!
lang11zi 2006-02-22
  • 打赏
  • 举报
回复
mislrb(上班看看早报,上上CSDN,下班看看电影

非常厉害
另外感谢各位支持!谢谢!
子陌红尘 2006-02-22
  • 打赏
  • 举报
回复
看错问题了,:)
子陌红尘 2006-02-22
  • 打赏
  • 举报
回复
前补0对齐(借用zlp321002的测试数据):
-------------------------------------------------------------------------
declare @t table(col1 int,col2 varchar(10))
insert into @t select 1,'10'
union all select 2,'7'
union all select 3,'8'
union all select 4,'6'
union all select 5,'长10'
--查询
select col1,
col2
from @t
order by right('0000000000'+col2,10)

/*
col1 col2
----------- ----------
4 6
2 7
3 8
1 10
5 长10
*/
zlp321002 2006-02-22
  • 打赏
  • 举报
回复
--支持小数的

declare @t table(col1 int,col2 varchar(10))
insert into @t select 1,'10'
union all select 2,'7'
union all select 3,'8'
union all select 4,'6'
union all select 5,'长10'
union all select 5,'短6.3'
--查询
select col1,
col2
from @t
order by cast(stuff(col2,1,patindex('%[0-9]%',col2)-1,'') as decimal(8,4)) asc
--结果
col1 col2
----------- ----------
4 6
5 短6.3
2 7
3 8
5 长10
1 10

(所影响的行数为 6 行)
OracleRoob 2006-02-22
  • 打赏
  • 举报
回复
按楼上这种,不支持小数
mislrb 2006-02-22
  • 打赏
  • 举报
回复
select col1,col2
from table1
order by isnumeric(col2) desc,case when isnumeric(col2)=1 then convert(int,col2) end
zlp321002 2006-02-22
  • 打赏
  • 举报
回复
--汉子是有规律的话.可以这么截取后,排序如下:

declare @t table(col1 int,col2 varchar(10))
insert into @t select 1,'10'
union all select 2,'7'
union all select 3,'8'
union all select 4,'6'
union all select 5,'长10'
--查询
select col1,
col2
from @t
order by cast(stuff(col2,1,patindex('%[0-9]%',col2)-1,'') as int) asc
--结果
col1 col2
----------- ----------
4 6
2 7
3 8
5 长10
1 10

(所影响的行数为 5 行)
OracleRoob 2006-02-22
  • 打赏
  • 举报
回复
判断如果是数值的,再按你的要求排序,其它的按你的要求作其它排序
OracleRoob 2006-02-22
  • 打赏
  • 举报
回复
/*
ISNUMERIC()函数
确定表达式是否为一个有效的数字类型。

*/
create table #t(col1 int,col2 varchar(20))

insert into #t(col1,col2)
select 1,'10' union all
select 2,'7' union all
select 3,'8' union all
select 4,'6' union all
select 5,'长10'

select *,ISNUMERIC(col2) as 是否数值
from #t

drop table #t
weisai 2006-02-22
  • 打赏
  • 举报
回复
如果col2值前面最多只有一个汉字,那么可以根据这个规律建一个视图
视图的效果如下,
col1 col2 col3
1 10 10
2 7 7
3 8 8
4 6 6
5 长10 10

那么就可以排序了,如果汉字的数目不定,那就没办法了。
lang11zi 2006-02-22
  • 打赏
  • 举报
回复
不行第
wfliu 2006-02-22
  • 打赏
  • 举报
回复
select * from table1 order by col2

34,587

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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