在Oracle数据库表中返回给定列的重复值及其出现次数的最简单SQL语句是什么?
例如:我有一个列为JOB_NUMBER的JOBS表。如何才能知道我是否有任何重复的JOB_NUMBERs,以及它们重复了多少次?
在Oracle数据库表中返回给定列的重复值及其出现次数的最简单SQL语句是什么?
例如:我有一个列为JOB_NUMBER的JOBS表。如何才能知道我是否有任何重复的JOB_NUMBERs,以及它们重复了多少次?
当前回答
做
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。
其他回答
1. 解决方案
select * from emp
where rowid not in
(select max(rowid) from emp group by empno);
另一种方法:
SELECT *
FROM TABLE A
WHERE EXISTS (
SELECT 1 FROM TABLE
WHERE COLUMN_NAME = A.COLUMN_NAME
AND ROWID < A.ROWID
)
当column_name上有索引时,工作正常(足够快)。它是删除或更新重复行的更好方法。
我通常使用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)
如何:
SELECT <column>, count(*)
FROM <table>
GROUP BY <column> HAVING COUNT(*) > 1;
要回答上面的例子,它看起来像:
SELECT job_number, count(*)
FROM jobs
GROUP BY job_number HAVING COUNT(*) > 1;
SELECT SocialSecurity_Number, Count(*) no_of_rows
FROM SocialSecurity
GROUP BY SocialSecurity_Number
HAVING Count(*) > 1
Order by Count(*) desc