我有一个没有任何主键的表,我希望它所有重复的记录

时间:2019-02-07 13:15:57

标签: sql

我有一个没有主键的表,我希望它所有重复的记录 表格-

EmpName  City
-------------
Shivam   Noida
Ankit    Delhi
Mani     Gurugram
Shivam   Faizabad
Mukesh   Noida

并想要这样的输出-

EmpName  City
-------------
Shivam   Noida   
Shivam   Faizabad
Mukesh   Noida

谢谢。

5 个答案:

答案 0 :(得分:3)

我认为你想要存在:

select t.*
from t
where exists (select 1
              from t t2
              where (t2.empname = t.empname and t2.city <> t.city) or
                    (t2.city = t.city and t2.empname <> t.empname)
             );

答案 1 :(得分:0)

使用existsor条件

with cte as
(
select 'Shivam' as name,  'Noida' as city union all
select 'Ankit' ,   'Delhi' union all
select 'Mani'   ,  'Gurugram' union all
select 'Shivam' ,  'Faizabad' union all
select 'Mukesh' ,  'Noida'

) select t1.* from cte t1 where exists ( select 1 from cte  t2
                                       where t1.name=t2.name
                                        group by name
                                        having count(*)>1
                                )
                                or exists
                                (
                                      select 1 from cte  t2
                                       where t1.city=t2.city
                                        group by city
                                        having count(*)>1
                                )

输出

name    city
Shivam  Noida
Shivam  Faizabad
Mukesh  Noida

答案 2 :(得分:0)

执行UNION ALL,将两种名称都放在一列中。 (d1)

GROUP BY其结果,并使用HAVING仅返回重复项(d2)。

JOIN

select EmpName, City
from tablename t1
join (select name from
      (select EmpName name from tablename
       union all
       select City from tablename) d1
      group by name
      having count(*) > 1) d2
  on d2.name in (EmpName, City)

答案 3 :(得分:-1)

您似乎正在寻找名称或城市也出现在表格另一行的所有行。

select *
from mytable
where city in (select city from mytable group by city having count(*) > 1)
   or empname in (select empname from mytable group by empname having count(*) > 1);

您说没有主键。这表明可能存在重复的行(名称和城市相同)。这使得在许多DBMS中无法在此处使用EXISTS来查找 other 行。这就是为什么我建议使用INCOUNT的原因。

答案 4 :(得分:-1)

select distinct * from table 
where col1 in (select col1 from table group by col1 having count(1) > 1)
or col2 in (select col2 from table group by col2 having count(1) > 1)