SQL:listing duplicate records from multiple join statements ?

浪尽此生 提交于 2019-12-10 23:23:22

问题


Helllo The below query is returning all the employees after joining multiple tables

   select e.* 
    from dbo.EMP e
    join dbo.HREMP a 
      on a.ID    = e.ID
    join dbo.LOGO c
      on c.EMPID = e.id 
    join dbo.LOGOACC d
      on d.BADGENO = c.BADGENO  
     and d.ACCLVID in (2191, 2292, 2293, 2294, 2295, 2296, 2297)

Total 653 Records were returning

Now after executing the below query

with EmployeeCTE as
(
   select e.* 
        from dbo.EMP e
        join dbo.HREMP a 
          on a.ID    = e.ID
        join dbo.LOGO c
          on c.EMPID = e.id 
        join dbo.LOGOACC d
          on d.BADGENO = c.BADGENO  
         and d.ACCLVID in (2191, 2292, 2293, 2294, 2295, 2296, 2297)
)
select k.id  from EmployeeCTE k
group  by ID
having count (k.id) >1

I found that there are 135 records having count more than 1 .

How to list all the records which is having more than one count?


回答1:


select * 
from (select e.*  
           , count(*) over (partition by e.id) as cnt
        from dbo.EMP e
        join dbo.HREMP a 
          on a.ID    = e.ID
        join dbo.LOGO c
          on c.EMPID = e.id 
        join dbo.LOGOACC d
          on d.BADGENO = c.BADGENO  
         and d.ACCLVID in (2191, 2292, 2293, 2294, 2295, 2296, 2297) 
     ) tt 
where tt.cnt > 1


来源:https://stackoverflow.com/questions/49468098/sqllisting-duplicate-records-from-multiple-join-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!