问题
I'm having trouble generating a query for this problem.
I have this small table
Tasks(employee_name, task)
Sample Data:
Tasks
------------------
Joe | taskA
Joe | taskB
Ted | taskA
Jim | taskB
Ray | taskA
Ray | taskB
John| taskA
Tim | taskC
I need to find all pairs of employees that have the exact same tasks.
For example using the data above the result set should be:
---------------------
employee1 | employee2
---------------------
Joe | Ray
Ted | John
I'm using mySQL for the database. Thanks!
回答1:
select a.employee_name,b.employee_name
from tasks as a, tasks as b
where a.employee_name>b.employee_name
group by a.employee_name,b.employee_name
having group_concat(distinct a.task order by a.task)=group_concat(distinct b.task order by b.task)
回答2:
Join the table to itself, pick one employee_name to be greater than the other, and where the tasks are equal.
select emp1.employee_name, emp2.employee_name, emp1.task
from tasks emp1
inner join task emp2
on emp1.employee_name > emp2.employee_name
and emp1.task = emp2.task
Hopefully you have a REAL PK, or this is just a sample exercise. This would not be good in a production environment since employee_name is not going to uniquely identify an employee in most companies/systems.
来源:https://stackoverflow.com/questions/17601834/sql-query-for-finding-pairs-that-share-the-exact-same-set-of-values