小编典典

SQL:列出来自多个连接语句的重复记录?

sql

Helllo下面的查询在加入多个表后返回所有员工

   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)

总计653条记录正在返回

现在执行以下查询后

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

我发现有135条记录的计数超过1。

如何列出具有多个计数的所有记录?


阅读 237

收藏
2021-03-08

共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
2021-03-08