sql - 分割字符串并返回mssql中最大的

标签 sql sql-server string-comparison

我需要找到一种方法来获取版本号最高的数据。

这是我的数据库设计:

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),PARSENAME(c,2), PARSENAME(c,3)
from a
order 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;为了弥补这一点,您必须填充适当的数字:

    -- 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   2010400
2.1.5   2010500
2.1.12  2011200
2.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 too
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, 
       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变为2112,2.2.1变为2221。 2.2.1大于2.1.12,不小于

关于sql - 分割字符串并返回mssql中最大的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6855588/

相关文章:

c# - 插入,选择,删除的SQL Server死锁

Python - 通过键中的汉明距离对 defaultdict 值进行分组

mysql - 如何从子查询中获取具体行来比较主查询中的值?

php - 如何仅在具有不同行的情况下更新 SQL

sql-server - T-SQL 相当于 Excel "MAX"函数,返回两个数字中较大的一个

SQL Group By 然后映射值是否存在

JavaScript:字符串与数字进行比较

python - 两个带有字符串的列表的相似度分数

c# - Linq to SQL 获取按日期分组的不同记录

php - Mysql(全文?)搜索产品