我正在尝试选择多次出现的记录,并且是特定部门和其他部门的一部分。
到目前为止,我的查询是:
SELECT employeeCode, employeeName
FROM
Employees
WHERE
Department <> 'Technology'
AND employeeCode IN (SELECT employeeCode
FROM Employees
GROUP BY employeeCode HAVING COUNT(*) > 1)
问题是我想选择属于技术部门的员工,但他们也参与其他部门。
所以,他们必须来自技术部门,但他们也可能来自家庭部门。在数据库中它可能看起来像:
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
所以基本上查询应该返回:
A3 | John |
A4 | Kim |
我认为这是我失踪的一小部分但是...... 有关如何过滤/排序以便始终使用该技术和其他部门的任何想法吗?
不过,我试过搜索,但我找不到像我这样的问题..答案 0 :(得分:2)
如果您希望员工可以加入技术部门和其他部门:
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;
这假设表中没有重复项。如果它可以有重复项,请使用count(distinct department) > 1
而不是count(*) > 1
。
答案 1 :(得分:0)
试试这个:
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;
答案 2 :(得分:0)
您可以将EXISTS与相关子查询连接在同一个具有不同条件的表上。
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')
答案 3 :(得分:0)
这适用于您的情况:
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