使用GROUP BY和HAVING COUNT(*)> 1来选择重复和中午重复字段

时间:2018-05-17 07:04:46

标签: oracle group-by count having-clause

以下是CUST_REF表格中的数据

CUST ID REF ID 1 7 2 2 3 5 4 5 5 5

以下查询将返回3 54 5

SELECT CUST_ID, REF_ID
FROM CUST_REF
WHERE REF_ID IN 
(select ref_id from CUST_REF
 group by ref_id
 having (count(*) > 1))
AND CUST_ID != REF_ID;

如果想要返回1 7 2 2 5 5怎么样?我在下面查询它只能返回1 72 2

SELECT CUST_ID, REF_ID
FROM CUST_REF
WHERE CUST_ID = REF_ID
AND REF_ID NOT IN 
(select ref_id from CUST_REF
group by ref_id
having (count(*) > 1))
UNION
SELECT CUST_ID, REF_ID
FROM CUST_REF
WHERE CUST_ID != REF_ID
AND REF_ID NOT IN 
(select ref_id from CUST_REF
group by ref_id
having (count(*) > 1));

1 个答案:

答案 0 :(得分:0)

您似乎想要选择REF_ID不重复的行,以及REF_ID = CUST_ID的行。如果是这样,那怎么样?

SQL> with cust_ref(cust_id, ref_id) as
  2  (select 1, 7 from dual union
  3   select 2, 2 from dual union
  4   select 3, 5 from dual union
  5   select 4, 5 from dual union
  6   select 5, 5 from dual
  7  )
  8  select cust_id, ref_id
  9  from cust_ref
 10  where ref_id not in (select ref_id
 11                       from cust_ref
 12                       group by ref_id
 13                       having count(*) > 1
 14                      )
 15     or ref_id = cust_id;

   CUST_ID     REF_ID
---------- ----------
         1          7
         2          2
         5          5

SQL>