SUBSTRING_INDEX用法

2024-01-03  本文已影响0人  闪闪亮晶晶mi

1. 定义

SUBSTRING_INDEX(str, delim, count)
str: 原始字符串,从中提取子字符串。
delim: 用于分隔字符串的分隔符。
count: 分隔符的序号

2.举例

(1)count是1的时候

SELECT SUBSTRING_INDEX('苹果,香蕉,橙子', ',', 1);

这将返回 苹果,因为它提取了第一个逗号之前的子字符串。
(2)count是-1的时候

SELECT SUBSTRING_INDEX('苹果,香蕉,橙子', ',', -1);

这将返回 橙子,因为它提取了最后一个逗号之后的子字符串。
(2)计数大于出现次数

SELECT SUBSTRING_INDEX('苹果,香蕉,橙子', ',', 5);

这将返回整个字符串,因为计数超过了分隔符的出现次数。

3.需求:求薪资最大值和最小值

-- 1、统一单位,未转换成元/月,那么千/月的用户需要乘以1000,万/月的用户需要乘以10000,万/年的用户需要乘以10000/12=833

create view data_salary_unit as
select *,(case 
    when salary like '%千/月' then 1000
    when salary like '%万/月' then 10000
    when salary like '%万/年' then 833 end) as unit
    from course

-- 2.在2的基础上取出薪资的最大值和最小值,先切割再乘以单位

SELECT
    *,case
    when unit = 1000 then CAST(SUBSTRING_INDEX(SUBSTRING_INDEX( salary, '千/月', 1 ), '-', 1 ) as decimal(6,2)) *unit
    when unit = 10000 then CAST(SUBSTRING_INDEX(SUBSTRING_INDEX( salary, '万/月', 1 ), '-', 1 ) as decimal(6,2)) *unit
    when unit = 833 then CAST(SUBSTRING_INDEX(SUBSTRING_INDEX( salary, '万/年', 1 ), '-', 1 ) as decimal(6,2)) *unit
    end AS min_salary,
    case
    when unit = 1000 then CAST(SUBSTRING_INDEX(SUBSTRING_INDEX( salary, '千/月', 1 ), '-', -1 ) as decimal(6,2)) *unit
    when unit = 10000 then CAST(SUBSTRING_INDEX(SUBSTRING_INDEX( salary, '万/月', 1 ), '-', -1 ) as decimal(6,2)) *unit
    when unit = 833 then CAST(SUBSTRING_INDEX(SUBSTRING_INDEX( salary, '万/年', 1 ), '-', -1 ) as decimal(6,2)) *unit
    end AS max_salary
FROM
    data_salary_unit

行后结果


image.png
上一篇 下一篇

猜你喜欢

热点阅读