How Can I Sort A #39;Version Number#39; Column Generically Using a SQL Server Query(如何使用 SQL Server 查询对“版本号列进行一般排序)
问题描述
我想知道我们中间的 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 函数(例如 left、right、substring、len, 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.
挑战
这篇关于如何使用 SQL Server 查询对“版本号"列进行一般排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用 SQL Server 查询对“版本号"列进行一般排序
基础教程推荐
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 无法解决整理冲突 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
