You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQL排序问题:如何让DelRef按数字顺序正确排序?

解决SQL排序问题

当前查询按字符串排序时,Del10、Del11会因字符串比较逻辑排在Del2之前,要实现自然排序,需提取字段中的数字部分按数值排序,同时保留前缀分组。以下是不同数据库的修正方案:

MySQL/MariaDB

select distinct ih_deliv as DelRef
from ihead
where ih_deliv <> ' ' and state <> 2
order by 
    substring(ih_deliv, 1, 3), -- 提取前缀"Del"部分
    cast(substring(ih_deliv, 4) as unsigned) -- 提取数字部分转为数值排序

SQL Server

select distinct ih_deliv as DelRef
from ihead
where ih_deliv <> ' ' and state <> 2
order by 
    left(ih_deliv, 3), -- 提取前缀"Del"
    cast(stuff(ih_deliv, 1, 3, '') as int) -- 移除前缀后转数值排序

Oracle

select distinct ih_deliv as DelRef
from ihead
where ih_deliv <> ' ' and state <> 2
order by 
    substr(ih_deliv, 1, 3), -- 提取前缀
    to_number(substr(ih_deliv, 4)) -- 提取数字转数值排序

思路说明

  • 先按固定前缀(此处为Del)排序,确保前缀相同的记录归为一组
  • 将字段中的数字部分转换为数值类型后排序,让10、11自然排在9之后

内容的提问来源于stack exchange,提问作者user3711598

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 12:42:04