问题描述
我有以下数据集:
FLD_NB|RGN_CD
1 |NC
2 |SC
1 |MA
3 |GA
3 |MA
我正在尝试识别所有超过1 RGN_CD
个可用的记录,例如在上述情况下,FLD_NB=1
和RGN_CD='NC'
都可以使用RGN_CD='MA'
识别跨FLD_NB
有RGN_CD
多个实例的行的最佳方法是什么?
解决方法
您可以使用group by
和having
:
select fld_nb
from mytable
group by fld_nb
having count(*) > 1
这为您提供了所有出现多次的fld_nb
。或者,如果您希望fld_nb
具有多个 rgn_cd
,则可以将hading子句更改为:
having count(distinct rgn_cd) > 1
,
可能这就是您需要的:
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;