我想知道是否可以为Oracle sql返回具有相同ID值的重复列的所有值
我的桌子设计如下
表A
Name ID Order Year
------ ------ ------- ------
JOHN 1 ORD123 2017
JAKE 2 ORD122 2018
JES 2 ORD111 2017
JOHN 3 ORD323 2012
NICK 4 ORD133 2011
AMY 4 ORD222 2010
MUS 4 ORD132 2010
我希望查询结果如下
Name ID Order Year
------ ------ ------- ------
JAKE 2 ORD122 2018
JES 2 ORD111 2017
NICK 4 ORD133 2011
AMY 4 ORD222 2010
MUS 4 ORD132 2010
答案 0 :(得分:2)
具有一个子查询以返回存在多次的id。
select *
from tableA
where id in (select id from tableA
group by id
having count(*) > 1)
答案 1 :(得分:2)
您可以使用分析功能在单个表扫描中执行此操作:
Oracle 11g R2架构设置:
CREATE TABLE TableA ( Name, ID, "Order", Year ) AS
SELECT 'JOHN', 1, 'ORD123', 2017 FROM DUAL UNION ALL
SELECT 'JAKE', 2, 'ORD122', 2018 FROM DUAL UNION ALL
SELECT 'JES', 2, 'ORD111', 2017 FROM DUAL UNION ALL
SELECT 'JOHN', 3, 'ORD323', 2012 FROM DUAL UNION ALL
SELECT 'NICK', 4, 'ORD133', 2011 FROM DUAL UNION ALL
SELECT 'AMY', 4, 'ORD222', 2010 FROM DUAL UNION ALL
SELECT 'MUS', 4, 'ORD132', 2010 FROM DUAL;
查询1 :
SELECT Name, ID, "Order", Year
FROM (
SELECT t.*,
COUNT(*) OVER ( PARTITION BY id ) AS num_duplicates
FROM tableA t
)
WHERE num_duplicates > 1
Results :
| NAME | ID | Order | YEAR |
|------|----|--------|------|
| JAKE | 2 | ORD122 | 2018 |
| JES | 2 | ORD111 | 2017 |
| NICK | 4 | ORD133 | 2011 |
| AMY | 4 | ORD222 | 2010 |
| MUS | 4 | ORD132 | 2010 |
在自联接中使用IN ( SELECT ... GROUP BY id HAVING COUNT(*) > 1 )
或聚合将需要两次表/索引扫描。
更新
如果我有两个病情,是否也可以病,可能是身分证和年份?
查询2 :只需将其他列添加到PARTITION BY
子句中:
SELECT Name, ID, "Order", Year
FROM (
SELECT t.*,
COUNT(*) OVER ( PARTITION BY id, year ) AS num_duplicates
FROM tableA t
)
WHERE num_duplicates > 1
Results :
| NAME | ID | Order | YEAR |
|------|----|--------|------|
| AMY | 4 | ORD222 | 2010 |
| MUS | 4 | ORD132 | 2010 |
答案 2 :(得分:1)
您可以使用where子句中的子查询,也可以使用重复的ID与主表之间的联接来实现。对于子查询方法,请检查jarlh的答案。
我认为对于大型表,应确保表已正确索引。
select
a.*
from
(
select id from tableA group by id having count(*) > 1
) dupes
inner join TableA a dupes on a.id = dupes.id