如何在 T-SQL 中获取版本号 (varchar) 列的最大值
我有一个这样定义的表:
Column: Version Message
Type: varchar(20) varchar(100)
----------------------------------
Row 1: 2.2.6 Message 1
Row 2: 2.2.7 Message 2
Row 3: 2.2.12 Message 3
Row 4: 2.3.9 Message 4
Row 5: 2.3.15 Message 5
我想编写一个 T-Sql 查询,它将获取 MAX 版本号的消息,其中“版本”列代表软件版本号。即,2.2.12 大于 2.2.7,2.3.15 大于 2.3.9 等。不幸的是,我想不出一种简单的方法来做到这一点,而不使用 CHARINDEX 或一些复杂的其他类似分割的逻辑。运行此查询:
SELECT MAX(Version) FROM my_table
将产生错误结果:
2.3.9,
而实际上应该是2.3.15。有什么好主意但不会太复杂吗?
I have a table defined like this:
Column: Version Message
Type: varchar(20) varchar(100)
----------------------------------
Row 1: 2.2.6 Message 1
Row 2: 2.2.7 Message 2
Row 3: 2.2.12 Message 3
Row 4: 2.3.9 Message 4
Row 5: 2.3.15 Message 5
I want to write a T-Sql query that will get message for the MAX version number, where the "Version" column represents a software version number. I.e., 2.2.12 is greater than 2.2.7, and 2.3.15 is greater than 2.3.9, etc. Unfortunately, I can't think of an easy way to do that without using CHARINDEX or some complicated other split-like logic. Running this query:
SELECT MAX(Version) FROM my_table
will yield the erroneous result:
2.3.9
When it should really be 2.3.15. Any bright ideas that don't get too complex?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种解决方案是使用表值拆分函数将版本拆分为行,然后将它们组合回列,以便您可以执行以下操作:
实际上,另一种方法是使用 PARSENAME 函数,该函数旨在拆分对象名称:
One solution would be to use a table-valued split function to split the versions into rows and then combine them back into columns so that you can do something like:
Actually, another way is to use the PARSENAME function which was meant to split object names:
它必须在大桌子上高效吗?我建议您创建一个索引持久计算列,将版本转换为正确排名的格式,并在查询中使用计算列。否则你总是会从头到尾地扫描。
如果桌子很小,那没关系。然后,您可以使用即时排名,使用 split 函数,或(ab)使用 Thomas 建议的解析名。
Does it have to be efficient on a large table? I suggest you create an indexed persisted computed column that transform the version into a format that ranks correctly, and use the computed column in your queries. Otherwise you'll always scan end to end.
If the table is small, it doesn't matter. Then you can use a just-in-time ranking, using a split function, or (ab)using the parsename as Thomas suggested.