简体   繁体   中英

Select records that appear more than once

I am trying to select records that appear more than once and are part of a specific department plus other departments.

So far the query that I have is this:

SELECT employeeCode, employeeName
FROM
    Employees
WHERE
    Department <> 'Technology' 
    AND employeeCode IN (SELECT employeeCode 
            FROM Employees 
            GROUP BY employeeCode HAVING COUNT(*) > 1)

The problem is that I want to select employees which are part of the Technology department, but they also participate in other departments.

So, they must be from the Technology department, but they could also be from the Household department. In the database it could look like:

1  |  A1  |  Alex  |  Technology
2  |  A2  |  Thor  |  Household
3  |  A3  |  John  |  Cars
4  |  A3  |  John  |  Technology
5  |  A4  |  Kim   |  Technology
6  |  A4  |  Kim   |  Video Games

So basically the query should return:

  A3  |  John  |  
  A4  |  Kim   | 

I think it's a small part that I am missing but.. Any ideas on how to filter/sort it so that it always uses the technology and the other departments?

Btw, I tried searching but I couldn't find a problem like mine..

If you want employees that could be in the technology department and another department:

select e.employeeCode, e.employeeName
from employees e
group by e.employeeCode, e.employeeName
having sum(case when e.department = 'Technology' then 1 else 0 end) > 0 and
       count(*) > 1;

This assumes no duplicates in the table. If it can have duplicates, then use count(distinct department) > 1 rather than count(*) > 1 .

Try this:

SELECT E.employeeCode, E.employeeName
FROM Employees E
INNER JOIN (SELECT DISTINCT E1.employeeCode, E1.employeeName
            FROM Employees E 
            WHERE E.Department = 'Technology'
           ) AS A ON E.employeeCode = A.employeeCode AND E.employeeName = A.employeeName
GROUP BY E.employeeCode, E.employeeName 
HAVING COUNT(*) > 1;

You can use EXISTS with correlated sub-query joining on the same table with different condition.

SELECT e1.employeeCode, e1.employeeName
FROM Employees e1
WHERE e1.Department = 'Technology' 
AND EXISTS (SELECT * FROM Employees e2 
            WHERE e1.employeeCode = e2.employeeCode 
            AND e2.Department <> 'Technology')

This will work for your case:

SELECT a.employeeCode, a.employeeName
FROM Employees a, Employees b
WHERE 
     a.Department = 'Technology'
     AND
     b.Department <> 'Technology'
     AND 
     a.employeeCode = b.employeeCode
     AND 
     a.employeeID <> b.employeeID

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM