【问题标题】:oracle sql to find the rows with one or more duplicate results in a same tableoracle sql在同一个表中查找具有一个或多个重复结果的行
【发布时间】:2021-04-23 09:20:43
【问题描述】:

我有以下示例数据集,我正在尝试提出一个查询以从同一个表中查找一个或多个重复行

表 A:2 列如下

CODE_NAME, RESULT 
ABC        1
BBC        1
ZZZ        5
ZZZ        6
ZZZ        7
KBC        2
ZBC        2
CCC        2
XYZ        3
MNC        4

我的输出应该在结果列中给出所有具有重复值的唯一行,如下所示

CODE_NAME, RESULT 
    ABC        1
    BBC        1       
    KBC        2
    ZBC        2
    CCC        2
   

我在下面尝试过,但它没有给我正确的结果 选择 A t1, A t2 其中 A.result = b.result 和 a.code_name b.code_name

欣赏其他建议。

【问题讨论】:

    标签: sql duplicates


    【解决方案1】:

    你可以使用exists:

    select t.*
    from t
    where exists (select 1
                  from t t2
                  where t2.result = t.result and t2.code_name <> t.code_name
                 );
    

    对于大型数据集的性能,您需要(result, code_name) 上的索引。

    您可能会发现每个重复结果一行更方便:

    select result,
           listagg(code_name, ',') within group (order by code_name)
    from t
    group by result
    having count(*) > 1;
    

    【讨论】:

    • 感谢您对我拥有的数据集的快速响应...存在需要一段时间才能运行,而 listagg 更快。谢谢你的建议。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多