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

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


当前回答

在多个列标识唯一行的情况下(例如关系表),你可以使用以下

使用行id 例如emp_dept(empid, deptid,开始日期,结束日期) 假设empid和deptid是唯一的,并在这种情况下标识行

select oed.empid, count(oed.empid) 
from emp_dept oed 
where exists ( select * 
               from  emp_dept ied 
                where oed.rowid <> ied.rowid and 
                       ied.empid = oed.empid and 
                      ied.deptid = oed.deptid )  
        group by oed.empid having count(oed.empid) > 1 order by count(oed.empid);

如果这样的表有主键,那么使用主键而不是rowid,例如id是pk那么

select oed.empid, count(oed.empid) 
from emp_dept oed 
where exists ( select * 
               from  emp_dept ied 
                where oed.id <> ied.id and 
                       ied.empid = oed.empid and 
                      ied.deptid = oed.deptid )  
        group by oed.empid having count(oed.empid) > 1 order by count(oed.empid);

其他回答

在多个列标识唯一行的情况下(例如关系表),你可以使用以下

使用行id 例如emp_dept(empid, deptid,开始日期,结束日期) 假设empid和deptid是唯一的,并在这种情况下标识行

select oed.empid, count(oed.empid) 
from emp_dept oed 
where exists ( select * 
               from  emp_dept ied 
                where oed.rowid <> ied.rowid and 
                       ied.empid = oed.empid and 
                      ied.deptid = oed.deptid )  
        group by oed.empid having count(oed.empid) > 1 order by count(oed.empid);

如果这样的表有主键,那么使用主键而不是rowid,例如id是pk那么

select oed.empid, count(oed.empid) 
from emp_dept oed 
where exists ( select * 
               from  emp_dept ied 
                where oed.id <> ied.id and 
                       ied.empid = oed.empid and 
                      ied.deptid = oed.deptid )  
        group by oed.empid having count(oed.empid) > 1 order by count(oed.empid);
SELECT   SocialSecurity_Number, Count(*) no_of_rows
FROM     SocialSecurity 
GROUP BY SocialSecurity_Number
HAVING   Count(*) > 1
Order by Count(*) desc 

你也可以尝试这样的方法在一个表中列出所有重复的值,比如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 *
FROM TABLE A
WHERE EXISTS (
  SELECT 1 FROM TABLE
  WHERE COLUMN_NAME = A.COLUMN_NAME
  AND ROWID < A.ROWID
)

当column_name上有索引时,工作正常(足够快)。它是删除或更新重复行的更好方法。

如果您不需要知道重复的实际数量,则甚至不需要在返回列中显示计数。如。

SELECT column_name
FROM table
GROUP BY column_name
HAVING COUNT(*) > 1