从多个表中查找重复行
Find Duplicate Rows from Multiple Tables
我有以下 table 结构:
用户
主键:UID
uid
DOB
1
1981-01-10
2
1981-01-10
3
1971-01-10
U_DETAILS
主键:UID、SEQUENCE
外键:UID
uid
sequence
name
1
11
Jack
1
12
Peter
2
13
Jack
2
14
Sam
3
15
Jill
3
16
Jill
我正在尝试从 USERS table 中检索多个用户具有相同 DOB 和姓名的行。
因此,在给定数据集中,应返回 UID 1 和 2。
有人可以帮忙设计一个查询吗?
如果您满足于将匹配的 uid 作为列表,则可以使用聚合:
select u.dob, ud.name,
listagg(u.uid, ',') within group (order by u.uid)
from users u join
u_details ud
on u.uid = ud.uid
group by u.dob, ud.name
having count(*) > 1;
如果你想要单独的行,那么我建议 exists
:
with ud as (
select u.uid, u.dob, ud.name
from users u join
u_details ud
on u.uid = ud.uid
)
select uid, dob, uname
from ud
where exists (select 1
from ud ud2
where ud2.dob = ud.dob and
ud2.name = ud.name and
ud2.uid <> ud.uid
);
编辑:
Window 函数可能更快:
with ud as (
select u.uid, u.dob, ud.name,
count(*) over (partition by u.dob, ud.name) as cnt
from users u join
u_details ud
on u.uid = ud.uid
)
select *
from ud
where cnt > 1;
我有以下 table 结构:
用户
主键:UID
uid | DOB |
---|---|
1 | 1981-01-10 |
2 | 1981-01-10 |
3 | 1971-01-10 |
U_DETAILS
主键:UID、SEQUENCE
外键:UID
uid | sequence | name |
---|---|---|
1 | 11 | Jack |
1 | 12 | Peter |
2 | 13 | Jack |
2 | 14 | Sam |
3 | 15 | Jill |
3 | 16 | Jill |
我正在尝试从 USERS table 中检索多个用户具有相同 DOB 和姓名的行。 因此,在给定数据集中,应返回 UID 1 和 2。
有人可以帮忙设计一个查询吗?
如果您满足于将匹配的 uid 作为列表,则可以使用聚合:
select u.dob, ud.name,
listagg(u.uid, ',') within group (order by u.uid)
from users u join
u_details ud
on u.uid = ud.uid
group by u.dob, ud.name
having count(*) > 1;
如果你想要单独的行,那么我建议 exists
:
with ud as (
select u.uid, u.dob, ud.name
from users u join
u_details ud
on u.uid = ud.uid
)
select uid, dob, uname
from ud
where exists (select 1
from ud ud2
where ud2.dob = ud.dob and
ud2.name = ud.name and
ud2.uid <> ud.uid
);
编辑:
Window 函数可能更快:
with ud as (
select u.uid, u.dob, ud.name,
count(*) over (partition by u.dob, ud.name) as cnt
from users u join
u_details ud
on u.uid = ud.uid
)
select *
from ud
where cnt > 1;