查找结果集中是否存在重复的字段值

时间:2012-12-27 10:13:03

标签: mysql oracle sql-server-2008

我有这样的结果集:

A    B
-------
1    10
2    10
2    10 
3    10
4    10
5    10

我选择对应于B的值的A的值,例如对应于10作为B的值。具有不同的A值,例如1,2,3,3,5。

我想知道,对于任何B的值,A中都有重复值。在这种情况下,重复2,所以在这种情况下答案是YES。

2 个答案:

答案 0 :(得分:3)

在标准ANSI SQL中,您只需使用GROUP BY:

select a, b
  from my_table
 group by a, b
having count(*) > 1

这将返回ab的每个组合,其中有多行,并且它将适用于指定的每个RDBMS。

答案 1 :(得分:0)

使用

SQL>   with data as (select rownum A ,   10 B from dual connect by level <= 5
  2                union all
  3                select 2 A ,   10 B from dual)
  4  select b, case when count(*) - count(distinct a) > 0 then 'YES' else 'NO' end has_dups
  5    from data
  6   group by b;

         B HAS
---------- ---
        10 YES

SQL>
SQL> with data as (select rownum A ,   10 B from dual connect by level <= 5
  2                union all
  3                select 2 A ,   10 B from dual)
  4  select b, a dup_val, count(*) number_of_dups
  5    from data
  6   group by b, a
  7   having count(*) > 1;

         B    DUP_VAL NUMBER_OF_DUPS
---------- ---------- --------------
        10          2              2