请大家帮忙,关于数据库排序问题?

chen7872 2003-11-03 11:08:48
根据一个字段(NO)排序,数据如下:
G101、G12、G23、G16、G23A、G12A、G206、G1、G206A
排列顺序如下:
G1、G12、G12A、G16、G23、G23A、G101、G206、G206A
请问如何写SQL进行排序?
...全文
24 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
txlicenhe 2003-11-03
  • 打赏
  • 举报
回复
order by cast(replace(replace(NO,'G',''),'A','') as int)
wzh1215 2003-11-03
  • 打赏
  • 举报
回复
还是zjcxc(邹建)的正确!
wzh1215 2003-11-03
  • 打赏
  • 举报
回复
应该是去掉前面的G就行了:
order by replace(NO,'G','')
zjcxc 元老 2003-11-03
  • 打赏
  • 举报
回复
--下面是数据测试
select * from(
select no='G101'
union all select 'G12'
union all select 'G23'
union all select 'G16'
union all select 'G23A'
union all select 'G12A'
union all select 'G206'
union all select 'G1'
union all select 'G206A'
) a order by cast(replace(replace(NO,'G',''),'A','') as int),no

--结果:
no
-----
G1
G12
G12A
G16
G23
G23A
G101
G206
G206A

(所影响的行数为 9 行)
zjcxc 元老 2003-11-03
  • 打赏
  • 举报
回复
上面的还错了一点,应该改为:
select * from 表 order by cast(replace(replace(NO,'G',''),'A','') as int),no

zjcxc 元老 2003-11-03
  • 打赏
  • 举报
回复
select * from 表 order by cast(replace(replace(NO,'G',''),'A','') as int)
pbsql 2003-11-03
  • 打赏
  • 举报
回复
去掉G、A,然后转换为整形排序:
order by convert(int,replace(replace(NO,'G',''),'A',''))
zjcxc 元老 2003-11-03
  • 打赏
  • 举报
回复
大力的更具有通用性.

pengdali 2003-11-03
  • 打赏
  • 举报
回复
如果他不只是A,如果有
G23B
G23C
呢?
pbsql 2003-11-03
  • 打赏
  • 举报
回复
越搞越复杂了

去掉G、A,然后转换为整形排序:
...order by convert(int,replace(replace(NO,'G',''),'A','')),NO
pengdali 2003-11-03
  • 打赏
  • 举报
回复
select * from(
select no='G101'
union all select 'G12'
union all select 'G23'
union all select 'G16'
union all select 'G23C'
union all select 'G23B'
union all select 'G23A'
union all select 'G12A'
union all select 'G206'
union all select 'G1'
union all select 'G206A'
) a order by

substring(no,2,

case when PATINDEX('%[^0123456789]%',substring(no,2,8000))=0
then 8000 else PATINDEX('%[^0123456789]%',substring(no,2,8000))-1 end)+0

,no

34,623

社区成员

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

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