我有以下表格列。
Manager(tabel)
| manager_id | manager_type |
1 X
2 Y
3 Z
Employee(table)
| emp_id | emp_name |
1 A
2 B
3 C
ManagerEmployee(table)
| id | manager_id | emp_id |
1 1 1
2 1 2
3 2 3
4 2 1
5 2 2
Workspace(table)
| id | manager_id | description | Revenue|
1 1 ...... 20
2 2 ...... 10
3 1 ...... 20
4 1 ...... 10
5 2 ...... 10
我想计算所有经理的工作区表的总收入。经理有manager_type =' X' (经理表)。该经理的员工与其他经理(ManagerEmployee表中提到的关系)合作。
请帮我解决这个问题?
答案 0 :(得分:2)
要从工作区获得收入总和,您可以使用与管理员表的连接,这可以通过
实现select
m.manager_id,
sum(w.Revenue)
from Workspace w
join Manager m on(m.manager_id = w.manager_id)
where m.manager_type ='X'
group by m.manager_id;
要了解为多个经理工作的员工,您可以计算并比较必须大于1的计数
select distinct m.*
from Manager m
join ManagerEmployee me on(m.manager_id = me.manager_id)
group by me.emp_id
having count(distinct me.manager_id) > 1
现在,对于您的最终任务,只有经理类型为X且其员工也为其他经理工作的总和,您可以将两个查询结合起来以产生您想要的结果
select
m.manager_id,
sum(w.Revenue)
from Workspace w
join Manager m on(m.manager_id = w.manager_id)
join (
select distinct m.*
from Manager m
join ManagerEmployee me on(m.manager_id = me.manager_id)
group by me.emp_id
having count(distinct me.manager_id) > 1
) mm
on (m.manager_id = mm.manager_id)
where m.manager_type ='X'
group by m.manager_id;
Demo