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
相关产品推荐
相关产品推荐

