【问题标题】:Filter Duplicated records in one column by another column SQL Netezza按另一列筛选一列中的重复记录 SQL Netezza
【发布时间】:2020-12-24 00:06:40
【问题描述】:

我有一个表,其中一行包含重复值:[A_Number],但其他没有,所以我需要使用另一个字段过滤这些重复记录:[Area_code],但[A_Number] 并不总是有重复值,

使用下面的例子:

Area_Code 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 有一个Area_Code 以9 开头并且有3 个数字,我们将从Area_Code 中删除9
  • 如果 A_Number A_Number 有一个 Area_Code 没有 9 和有 2 个数字将是相同的
  • [已编辑] A_Number 可能有不同的 Area_Code,例如 A_Number:2324356

预期结果

Area_Code A_Number
55 2324356
45 2324356
40 8675643
13 4450987

【问题讨论】:

    标签: sql filter netezza


    【解决方案1】:

    如果area_code 总是重复最后两位数字,即9xxxx(其中xx 在所有情况下都是相同的),那么一个简单的group by 和适当的子字符串就可以解决-

    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, case 
                       when area_code like '9%' 
                         then substring(area_code, 2)
                       else area_code
                     end as code
        from t
        group by a_number, code ) tmp
    group by a_number
    

    【讨论】:

    • 是的area_code xx 是不同的数字,并且有可能具有不同的area_code 的唯一a_number 就像线程中的示例一样
    【解决方案2】:

    这回答了问题的原始版本。

    认为你基本上想要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;
    

    【讨论】:

    • 对不起,我有一个编辑,因为 A_Number 可能有不同的 Area_Code,例如示例中的 A_Number:2324356
    猜你喜欢
    • 2019-02-26
    • 1970-01-01
    • 2021-03-21
    • 2015-11-30
    • 2013-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-21
    • 1970-01-01
    相关资源
    最近更新 更多