【问题标题】:Identify duplicates within columns using sql (oracle)使用 sql (oracle) 识别列中的重复项
【发布时间】:2021-01-03 16:01:00
【问题描述】:

我有以下数据集:

FLD_NB|RGN_CD
1     |NC
2     |SC
1     |MA
3     |GA
3     |MA

我正在尝试识别超过 1 个RGN_CD 中可用的所有记录,例如在上述场景中,FLD_NB=1RGN_CD='NC'RGN_CD='MA' 中都可用

识别在RGN_CD 中具有多个FLD_NB 实例的行的最佳方法是什么?

【问题讨论】:

  • 请添加示例数据和预期结果...
  • FLD_NB=3 呢,应该也是这样的候选人之一吧?
  • 请提供所需结果的示例

标签: sql oracle count duplicates having-clause


【解决方案1】:

您可以使用group byhaving

select fld_nb
from mytable
group by fld_nb
having count(*) > 1

这将为您提供所有出现多次的fld_nbs。或者,如果您希望 fld_nbs 有多个 distinct rgn_cd,您可以将 having 子句更改为:

having count(distinct rgn_cd) > 1

【讨论】:

  • 我认为这将适用于我特别寻找的内容 - 我减少了结果集中的列数,然后我认为我可以使用此查询获得正确的结果 - 我仍在检查但所以远看起来不错 - 非常感谢
【解决方案2】:

可能这就是你需要的:

select *
from (
     select t.*
           ,count(*)over(partition by FLD_NB) cnt
     from t
     )
where cnt>1;

带有结果的完整测试用例:

with t (FLD_NB,RGN_CD) as (
select 1, 'NC' from dual union all
select 2, 'SC' from dual union all
select 1, 'MA' from dual union all
select 3, 'GA' from dual union all
select 3, 'MA' from dual 
)
select *
from (
     select t.*
           ,count(*)over(partition by FLD_NB) cnt
     from t
     )
where cnt>1;

结果:

    FLD_NB RG        CNT
---------- -- ----------
         1 NC          2
         1 MA          2
         3 MA          2
         3 GA          2

如果您只需要计算不同的值:

select *
from (
     select t.*
           ,count(distinct RGN_CD)over(partition by FLD_NB) cnt
     from t
     )
where cnt>1;

【讨论】:

  • 是的,这是我期待的结果集,但是这个表像往常一样有很多其他列以及这两个主要列,我必须在这些列上识别重复项 - 我通过更改列名到主要的 2 列但是结果集仍然抛出更多我不想看到的行...例如如果我有 FLD_NB=22 并且它有 7 行具有相同的 RGN_CD=NA 仍然返回那些我不希望的行,因为 FLD_NM=22 不会在任何其他 RGN_CD 中重复
  • @sourabhbhattacharya 啊,好的,所以只需将count(*)over 更改为count(distinct RGN_CD) over
  • 太好了,所以请将答案标记为适合您的正确 ID
猜你喜欢
  • 2011-11-16
  • 2020-12-20
  • 2011-01-30
  • 2018-07-04
  • 2022-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多