问题描述
我有一个表,其中一行包含重复值:[A_Number]
但其他的不是,所以我需要使用另一个字段过滤这些重复记录:[Area_code]
,但是 [A_Number]
并不总是有重复的值,
使用以下示例:
区域代码 | A_Number |
---|---|
955 | 2324356 |
55 | 2324356 |
945 | 2324356 |
45 | 2324356 |
940 | 8675643 |
13 | 4450987 |
- 问题是:由于
A_Number
,Area_Code
可能有重复的记录,每个重复的A_Number
都有 2 个Area_Code
,其中一个以9
开头,并且有 3 个数字但另一个没有9
并且有 2 位数字,所以我需要获取没有9
的 Area_Code 并且只有 2 位数字。 - 如果
A_Number
有一个以 9 开头且有 3 个数字的Area_Code
,我们将从9
中删除Area_Code
- 如果 A_Number
A_Number
有一个Area_Code
,没有 9 和有 2 个数字将是相同的 - [编辑]
A_Number
可以有不同的Area_Code
,如A_Number
:2324356
预期结果
区域代码 | A_Number |
---|---|
55 | 2324356 |
45 | 2324356 |
40 | 8675643 |
13 | 4450987 |
解决方法
如果 area_code
将始终重复最后两位数字,即 9xx
和 xx
(其中 xx
在所有出现中都相同),那么具有适当子字符串的简单分组将起作用出 -
select a_number,case
when area_code like '9%'
then substring(area_code,2)
else area_code
end as code
from t
group by a_number,code
但是,如果 xx
是不同的数字,那么您必须选择如何将它们限制为您想要的数字
-- take only the first (min) or last (max)
select a_number,min(code) as first_code,max(code) as last_code
from
select a_number,2)
else area_code
end as code
from t
group by a_number,code ) tmp
group by a_number
,
这回答了问题的原始版本。
我认为你基本上想要 min()
带有一些字符串解析逻辑:
select a_number,(case when min(area_code) like '9%'
then substring(min(area_code),2)
else min(area_code)
end)
from t
group by a_number;