如何使用 SQL Server 查询对“版本号"列进行一般排序

2021-12-10 00:00:00 sql sorting sql-server sql-server-2000

我想知道我们中间的 SQL 天才是否可以向我伸出援助之手.

I wonder if the SQL geniuses amongst us could lend me a helping hand.

我在表 Versions 中有一列 VersionNo 包含版本号"值,例如

I have a column VersionNo in a table Versions that contains 'version number' values like

VersionNo
---------
1.2.3.1
1.10.3.1
1.4.7.2

我想对此进行排序,但不幸的是,当我执行标准的 order by 时,它被视为字符串,因此顺序显示为

I am looking to sort this, but unfortunately, when I do a standard order by, it is treated as a string, so the order comes out as

VersionNo
---------
1.10.3.1
1.2.3.1
1.4.7.2

以下是我所追求的:

VersionNo
---------
1.2.3.1
1.4.7.2
1.10.3.1

所以,我需要做的是按相反顺序按数字排序(例如,在 a.b.c.d 中,我需要按 d,c,b,a 排序以获得正确的排序).

So, what I need to do is to sort by the numbers in reverse order (e.g. in a.b.c.d, I need to sort by d,c,b,a to get the correct sort ourder).

但我不知道如何以通用方式实现这一目标.当然,我可以使用各种 sql 函数(例如 leftrightsubstringlen, charindex),但我不能保证版本号总是有 4 个部分.我可能有这样的列表:

But I am stuck as to how to achieve this in a GENERIC way. Sure, I can split the string up using the various sql functions (e.g. left, right, substring, len, charindex), but I can't guarantee that there will always be 4 parts to the version number. I may have a list like this:

VersionNo
---------
1.2.3.1
1.3
1.4.7.2
1.7.1
1.10.3.1
1.16.8.0.1

可以,有人有什么建议吗?非常感谢您的帮助.

Can, does anyone have any suggestions? Your help would be much appreciated.

推荐答案

如果您使用的是 SQL Server 2008

If You are using SQL Server 2008

select VersionNo from Versions order by cast('/' + replace(VersionNo , '.', '/') + '/' as hierarchyid);

什么是hierarchyid

2000、2005、2008 年的解决方案:此处为 T-SQL 排序挑战的解决方案.

Solutions for 2000, 2005, 2008: Solutions to T-SQL Sorting Challenge here.

挑战

相关文章