求助:提取不同客户薪资类别中的最小与最大值
解决薪资类别极值提取问题
原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
代码说明
- 类别提取:用
trim()去除原结果中多余的空格(比如A:后面的多个连续空格),让输出更整洁。 - min_level处理:
- 含
-的常规类别:沿用原逻辑提取分隔符左侧的数值; - L类(300,000 and above):用正则表达式匹配字符串中的千分位数字格式,提取300,000作为最小值;
- 其他特殊类(如A类):保留null。
- 含
- max_level处理:
- 含
-的常规类别:调整原逻辑,直接从-右侧开始截取并去除空格,避免原代码固定起始位置的局限性; - A类(below 30,000):用正则匹配提取30,000作为最大值;
- 其他特殊类(如L类):保留null。
- 含
预期结果
| cust_income_level | category | min_level | max_level |
|---|---|---|---|
| G: 130,000 - 149,999 | G: | 130,000 | 149,999 |
| K: 250,000 - 299,999 | K: | 250,000 | 299,999 |
| A: Below 30,000 | A: | null | 30,000 |
| L: 300,000 and above | L: | 300,000 | null |
内容的提问来源于stack exchange,提问作者katarzynat
相关产品推荐
相关产品推荐

