使用 GROUP BY 和 HAVING COUNT(*) >1 到 select 重复和非重复字段
Using GROUP BY and HAVING COUNT(*) >1 to select duplicate and non-duplicate field
下面是CUST_REF
table
中的数据
CUST ID REF ID
1 7
2 2
3 5
4 5
5 5
下面的查询将 return 3 5
和 4 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;
如果想return1 7
2 2
5 5
怎么样?我在下面查询它只能 return 1 7
和 2 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));
您似乎想要 select 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>
下面是CUST_REF
table
CUST ID REF ID
1 7
2 2
3 5
4 5
5 5
下面的查询将 return 3 5
和 4 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;
如果想return1 7
2 2
5 5
怎么样?我在下面查询它只能 return 1 7
和 2 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));
您似乎想要 select 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>