SQL 对版本进行排序遇到的问题

背景

物料存在多个版本,我们每次只需要使用最新的版本

问题

  • 问题1:版本使用的是字符串,倒序排序,会导致 版本8 会排在版本11 前面
  • 问题2:版本version字符串既有数字字符串,也有字母字符串

解决思路

  • 对于数字字符串,需要将其转换成整数,
  • 字母字符串则转换成对应的ASCII码值

SQL语句

原本语句

sql 复制代码
    SELECT 
        material_code AS material_code_in,
        material_name AS material_name_in,
        '' AS material_type_in,
        material_class_small AS material_class_small_in,
        material_class_big AS material_class_big_in,
        erp_code AS erp_code_in,
        version AS version_in,
        unit AS unit_in
    FROM tbl_material_info 
    WHERE material_code IN ('P120','P525A','2070039115')

改写语句

sql 复制代码
WITH RankedMaterials AS (
    SELECT 
        material_code AS material_code_in,
        material_name AS material_name_in,
        '' AS material_type_in,
        material_class_small AS material_class_small_in,
        material_class_big AS material_class_big_in,
        erp_code AS erp_code_in,
        version AS version_in,
        unit AS unit_in,
        ROW_NUMBER() OVER (
            PARTITION BY material_code 
            ORDER BY 
                CASE 
                    WHEN TRY_CAST(version AS INT) IS NOT NULL THEN TRY_CAST(version AS INT) 
                    ELSE ASCII(SUBSTRING(version, 1, 1)) -- 将字母字符串转换为对应的ASCII码值
                END DESC
        ) AS rn
    FROM tbl_material_info 
    WHERE material_code IN ('P120','P525A','2070039115')
)
SELECT 
    material_code_in,
    material_name_in,
    material_type_in,
    material_class_small_in,
    material_class_big_in,
    erp_code_in,
    version_in,
    unit_in
FROM RankedMaterials
WHERE rn = 1;
相关推荐
跟着珅聪学java1 小时前
spring boot +Elment UI 上传文件教程
java·spring boot·后端·ui·elementui·vue
我命由我123451 小时前
Spring Boot 自定义日志打印(日志级别、logback-spring.xml 文件、自定义日志打印解读)
java·开发语言·jvm·spring boot·spring·java-ee·logback
lilye661 小时前
程序化广告行业(55/89):DMP与DSP对接及数据统计原理剖析
java·服务器·前端
·薯条大王4 小时前
MySQL联合查询
数据库·mysql
战族狼魂5 小时前
CSGO 皮肤交易平台后端 (Spring Boot) 代码结构与示例
java·spring boot·后端
xyliiiiiL6 小时前
ZGC初步了解
java·jvm·算法
杉之6 小时前
常见前端GET请求以及对应的Spring后端接收接口写法
java·前端·后端·spring·vue
morris1316 小时前
【redis】redis实现分布式锁
数据库·redis·缓存·分布式锁
hycccccch7 小时前
Canal+RabbitMQ实现MySQL数据增量同步
java·数据库·后端·rabbitmq
这个懒人7 小时前
深入解析Translog机制:Elasticsearch的数据守护者
数据库·elasticsearch·nosql·translog