Apostrofix
Apostrofix

Reputation: 2180

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..

Upvotes: 0

Views: 1917

Answers (4)

anishroniyar
anishroniyar

Reputation: 96

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

Upvotes: 0

Nenad Zivkovic
Nenad Zivkovic

Reputation: 18559

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')

Upvotes: 0

Saharsh Shah
Saharsh Shah

Reputation: 29051

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;

Upvotes: 0

Gordon Linoff
Gordon Linoff

Reputation: 1269553

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.

Upvotes: 2

Related Questions