栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

拆分字符串并在mssql中返回最大

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

拆分字符串并在mssql中返回最大

试试这个:

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),PARSENAME(c,2), PARSENAME(c,3)from aorder by convert(int,PARSENAME(c,3)),convert(int,PARSENAME(c,2)),convert(int,PARSENAME(c,1))

灵感来自:http :
//www.sql-server-helper.com/tips/sort-ip-address.aspx

with a as(    select * from (values    ('1.1.2'),('1.1.3'),('2.1.4 '), ('2.1.5'), ('2.2.1') ) as b(c)),x as (    select c,        convert(int,PARSENAME(c,3)) * 100        + convert(int,PARSENAME(c,2)) * 10        + convert(int,PARSENAME(c,1)) * 1 as the_value    from a)select c from x where the_value = (select MAX(the_value) from x)

在软件开发中,通常会找到一个包含两个数字的次要版本号,该版本号与该数字的值没有任何关系,因此版本1.12大于1.5;否则,版本号不大于1.5。为了弥补这一点,您必须适当
填充 数字:

    -- Use this, the query above is not future-proof :-)with a as(    select * from (values    ('2.1.4 '), ('2.1.12'), ('2.1.5'), ('2.2.1') ) as b(c)),x as (    select c,        convert(int,PARSENAME(c,3)) * 100*100*100        + convert(int,PARSENAME(c,2)) * 100*100        + convert(int,PARSENAME(c,1)) * 100 as the_value    from a)select c, the_value from x   order by the_value

输出:

2.1.4   20104002.1.5   20105002.1.12  20112002.2.1   2020100

如果您不考虑这一点(与以下查询一样):

with a as(    select * from (values    ('2.1.4 '), ('2.1.12'), ('2.1.5'), ('2.2.1') ) as b(c)),x as (    select c,        convert(int,PARSENAME(c,3)) * 100       + convert(int,PARSENAME(c,2)) * 10       + convert(int,PARSENAME(c,1)) * 1 as the_value    from a)select c, the_value from x   order by the_value;    -- KorsG's answer has a bug toowith a as(    select * from (values    ('2.1.4 '), ('2.1.12'), ('2.1.5'), ('2.2.1') ) as b(c)),x as (    select c,        CAST(REPLACE(c, '.', '') AS int) as the_value    from a)select c, the_value from x   order by the_value

这两个查询将产生相同(不正确)的输出:

cthe_value2.1.4   2142.1.5   2152.2.1   2212.1.12  222

2.2.1和2.1.12的值重叠。当您只删除点并将结果字符串直接转换为int时,也会发生这种情况。2.1.12变成212,2.2.1变成212。2.2.1大于2.1.12,不小于



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/670381.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号