You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:提取不同客户薪资类别中的最小与最大值

解决薪资类别极值提取问题

原SQL的问题在于依赖字符串中的-分隔符定位数值,但特殊类别(A: below 30,000、L: 300,000 and above)不含该分隔符,导致instr()返回0,最终substr()生成空值。可以通过CASE条件分支结合字符串匹配函数处理不同类别:

优化后的SQL代码

select distinct
    cust_income_level,
    -- 提取类别标识并去除多余空格
    trim(substr(cust_income_level, 1, instr(cust_income_level, ' '))) as category,
    -- 处理最小薪资字段
    case
        when instr(cust_income_level, '-') > 0 then trim(substr(cust_income_level, 3, instr(cust_income_level, '-') - 4))
        when cust_income_level like 'L:%' then trim(regexp_substr(cust_income_level, '\d{1,3}(,\d{3})+'))
        else null
    end as min_level,
    -- 处理最大薪资字段
    case
        when instr(cust_income_level, '-') > 0 then trim(substr(cust_income_level, instr(cust_income_level, '-') + 2))
        when cust_income_level like 'A:%' then trim(regexp_substr(cust_income_level, '\d{1,3}(,\d{3})+'))
        else null
    end as max_level
from
    sh.customers

代码说明

  1. 类别提取:用trim()去除原结果中多余的空格(比如A:后面的多个连续空格),让输出更整洁。
  2. min_level处理:
    • 含-的常规类别:沿用原逻辑提取分隔符左侧的数值;
    • L类(300,000 and above):用正则表达式匹配字符串中的千分位数字格式,提取300,000作为最小值;
    • 其他特殊类(如A类):保留null。
  3. max_level处理:
    • 含-的常规类别:调整原逻辑,直接从-右侧开始截取并去除空格,避免原代码固定起始位置的局限性;
    • A类(below 30,000):用正则匹配提取30,000作为最大值;
    • 其他特殊类(如L类):保留null。

预期结果

cust_income_levelcategorymin_levelmax_level
G: 130,000 - 149,999G:130,000149,999
K: 250,000 - 299,999K:250,000299,999
A: Below 30,000A:null30,000
L: 300,000 and aboveL:300,000null

内容的提问来源于stack exchange,提问作者katarzynat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 13:01:13