核心 ANSI SQL-99 兼容:
select * from product
order by cast(version as int),
cast(substring(version from position('.' in version) + 1) as int);
即首先按整数部分排序。.
然后按字符后面的“整数”排序。
执行为:
SQL>create table product (version varchar(10), name varchar(10));
SQL>insert into product values ('1.8', 'Bar');
SQL>insert into product values ('12.23', 'Foo');
SQL>insert into product values ('23.15', 'Hello');
SQL>insert into product values ('1.11', 'Bye');
SQL>select * from product
SQL&order by cast(version as int),
SQL& cast(substring(version from position('.' in version) + 1) as int);
version name
========== ==========
1.8 Bar
1.11 Bye
12.23 Foo
23.15 Hello
4 rows found
请注意,某些产品有自己的 ANSI SQLsubstring()
和position()
. 如果您遇到麻烦,请尝试substr(version, value)
等。
编辑:(cast(version as int) 对于包含小数的字符串在 SQL Server(和 Postgres)中将失败 – a_horse_with_no_name )确保只将整数部分转换为整数:
select * from product
order by cast(substring(version from 1 for position('.' in version) -1) as int),
cast(substring(version from position('.' in version) + 1) as int);