现在我有两个表:项目和项目工作者。
项目包含项目名称及其项目ID projectworker保存项目ID以及哪个worker id已经处理它。
一个worker可以处理多个项目,一个项目可以有一个以上的worker(如果有多个与之关联的worker,那么项目id将重复多次,每个worker都有一行)。
我需要找到参与多个项目的大多数工人的项目。
我找到了使用此子查询处理过多个项目的工作人员:
SELECT worker_id
FROM projectworker
GROUP BY worker_id
HAVING COUNT(worker_id) >= 2
返回三个工人ID(1,3和12)
现在,我如何搜索项目工作者表,找出哪三个工作人员中的大多数都在哪个项目上工作?
答案 0 :(得分:1)
因此,首先找到从事过多个项目的工人:
select worker_id, count(*) as numprojects
from project_worker
group by worker_id
having count(*) > 1;
然后,将其用于项目的过滤器:
select pw.*
from project_workers pw
where pw.worker_id in (select worker_id
from project_workers
group by worker_id
having count(*) > 1
)
然后你可以添加group by
并按这些工人的数量排序:
select pw.project_id, count(*)
from project_workers pw
where pw.worker_id in (select worker_id
from project_workers
group by worker_id
having count(*) > 1
)
group by pw.project_id
order by count(*) desc;
这将按照该标准按顺序为您提供项目列表。
答案 1 :(得分:1)
您可以像这样查询同一个表:
SELECT project_id, COUNT(worker_id)
FROM projectworker
WHERE worker_id IN
(SELECT worker_id
FROM projectworker
GROUP BY worker_id
HAVING COUNT(worker_id) >= 2)
GROUP BY project_id
ORDER BY COUNT(worker_id) DESC