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;
相关推荐
Hacker_LaoYi27 分钟前
【渗透技术总结】SQL手工注入总结
数据库·sql
岁月变迁呀29 分钟前
Redis梳理
数据库·redis·缓存
独行soc30 分钟前
#渗透测试#漏洞挖掘#红蓝攻防#护网#sql注入介绍06-基于子查询的SQL注入(Subquery-Based SQL Injection)
数据库·sql·安全·web安全·漏洞挖掘·hw
神仙别闹1 小时前
基于java的改良版超级玛丽小游戏
java
你的微笑,乱了夏天1 小时前
linux centos 7 安装 mongodb7
数据库·mongodb
黄油饼卷咖喱鸡就味增汤拌孜然羊肉炒饭1 小时前
SpringBoot如何实现缓存预热?
java·spring boot·spring·缓存·程序员
工业甲酰苯胺1 小时前
分布式系统架构:服务容错
数据库·架构
暮湫2 小时前
泛型(2)
java
超爱吃士力架2 小时前
邀请逻辑
java·linux·后端
南宫生2 小时前
力扣-图论-17【算法学习day.67】
java·学习·算法·leetcode·图论