拆分一个字符串并在mssql中返回最大值
发布时间:2020-12-12 07:27:19 所属栏目:MsSql教程 来源:网络整理
导读:我需要找到一种方法来获取具有最高版本号的数据. 这是我的数据库设计: VERSIONNUMBER - varchar(15)DOWNLOADPATH - varchar(100) 可以说我有以下记录: VERSIONNUMBER -------- DOWNLOADPATH1.1.2 a.com1.1.3 b.com2.1.4 c.com2.1.5 d.com2.2.1 e.com 我需要
我需要找到一种方法来获取具有最高版本号的数据.
这是我的数据库设计: VERSIONNUMBER - varchar(15) DOWNLOADPATH - varchar(100) 可以说我有以下记录: VERSIONNUMBER -------- DOWNLOADPATH 1.1.2 a.com 1.1.3 b.com 2.1.4 c.com 2.1.5 d.com 2.2.1 e.com 我需要使用版本号2.2.1获取记录.需要一些sql的帮助:) 感谢您的任何帮助 解决方法试试这个:with a as ( select * from (values ('1.1.2'),('1.1.3'),('2.1.4 '),('2.1.5'),('2.2.1') ) as b(c) ) select c,PARSENAME(c,1),2),3) from a order by convert(int,3)),convert(int,2)),1)) 灵感来自:http://www.sql-server-helper.com/tips/sort-ip-address.aspx with a as ( select * from (values ('1.1.2'),('2.2.1') ) as b(c) ),x as ( select c,3)) * 100 + convert(int,2)) * 10 + convert(int,1)) * 1 as the_value from a ) select c from x where the_value = (select MAX(the_value) from x) 在软件开发中,通常会找到一个包含两位数的次要版本号,版本号与数字值没有任何关系,因此版本1.12大于1.5;为了弥补这一点,你必须充分填充数字: -- Use this,the query above is not future-proof :-) with a as ( select * from (values ('2.1.4 '),('2.1.12'),3)) * 100*100*100 + convert(int,2)) * 100*100 + convert(int,1)) * 100 as the_value from a ) select c,the_value from x order by the_value 输出: 2.1.4 2010400 2.1.5 2010500 2.1.12 2011200 2.2.1 2020100 如果您不考虑这一点(如下面的查询): with a as ( select * from (values ('2.1.4 '),3)) * 100 + convert(int,2)) * 10 + convert(int,1)) * 1 as the_value from a ) select c,the_value from x order by the_value; -- KorsG's answer has a bug too with a as ( select * from (values ('2.1.4 '),CAST(REPLACE(c,'.','') AS int) as the_value from a ) select c,the_value from x order by the_value 这两个查询将产生相同(不正确)的输出: c the_value 2.1.4 214 2.1.5 215 2.2.1 221 2.1.12 222 2.2.1和2.1.12的值重叠.当您仅删除点并将结果字符串直接转换为int时,也会发生这种情况. 2.1.12成为二千一百二十二,2.2.1成为二百二十二. 2.2.1大于2.1.12,不小于 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |