在Oracle数据库表中返回给定列的重复值及其出现次数的最简单SQL语句是什么?

例如:我有一个列为JOB_NUMBER的JOBS表。如何才能知道我是否有任何重复的JOB_NUMBERs,以及它们重复了多少次?


当前回答

你也可以尝试这样的方法在一个表中列出所有重复的值,比如reqitem

SELECT count(poid) 
FROM poitem 
WHERE poid = 50 
AND rownum < any (SELECT count(*)  FROM poitem WHERE poid = 50) 
GROUP BY poid 
MINUS
SELECT count(poid) 
FROM poitem 
WHERE poid in (50)
GROUP BY poid 
HAVING count(poid) > 1;

其他回答

我能想到的最简单的:

select job_number, count(*)
from jobs
group by job_number
having count(*) > 1;

select count(j1.job_number), j1.job_number, j1.id, j2.id
from   jobs j1 join jobs j2 on (j1.job_numer = j2.job_number)
where  j1.id != j2.id
group by j1.job_number

将给出复制行的id。

我通常使用Oracle分析函数ROW_NUMBER()。

假设您想检查构建在列(c1, c2, c3)上的唯一索引或主键的副本。 然后你将这样做,打开ROW_NUMBER()带来的行数为>1的行数的ROWID s:

Select *
From Table_With_Duplicates
Where Rowid In (Select Rowid
                  From (Select ROW_NUMBER() Over (
                                 Partition By c1, c2, c3
                                 Order By c1, c2, c3
                               ) nbLines
                          From Table_With_Duplicates) t2
                 Where nbLines > 1)

按COUNT聚合列,然后使用HAVING子句查找出现多次的值。

SELECT column_name, COUNT(column_name)
FROM table_name
GROUP BY column_name
HAVING COUNT(column_name) > 1;

我知道这是一个老帖子,但这可能会帮助一些人。

如果你需要打印表的其他列,同时检查重复使用如下:

select * from table where column_name in
(select ing.column_name from table ing group by ing.column_name having count(*) > 1)
order by column_name desc;

如果需要,还可以在where子句中添加一些额外的过滤器。