我按照以下方式设计了一个组织表:
Name Supervisor Manager
David - -
Josseph David -
Jenny Josseph David
Step Josseph David
Mike Josseph David
steven David
上面的图表解释说,大卫处于组织的最高位置,约瑟夫和史蒂文向大卫报告; Jenny,step and mike向Josseph汇报。
我想知道有多少人向大卫汇报;和大卫是多少人的经理?这是我预期的表格:
Supervisor Manager
2 3
只能使用1个查询吗?
答案 0 :(得分:3)
http://sqlfiddle.com/#!9/f39ce/2
SELECT SUM(IF(Supervisor='David',1,0)),
SUM(IF(manager='David',1,0))
FROM mytable
以下是分组查询的示例,如果您需要的话:
http://sqlfiddle.com/#!9/bdd738/5
SELECT t1.name,
SUM(IF(t1.name=t2.Supervisor,1,0)),
SUM(IF(t1.name=t2.manager,1,0))
FROM mytable t1
LEFT JOIN mytable t2
ON t1.name = t2.Supervisor
OR t1.name = t2.manager
GROUP BY t1.name;
答案 1 :(得分:2)
它可以:
select Name as BossName,
sum( case when Supervisor = Name then 1 else 0 end) as Supervises,
sum( case when Manager = Name then 1 else 0 end) as Manages
from your_table group by Name;
这会得到类似的东西:
BossName Supervises Manages
David 2 3
Josseph 3 0
Jenny 0 0
.... 0 0
答案 2 :(得分:1)
使用以下查询
select name,(select count(*) from <table> where supervisor=name) as supervisor,
(select count(*) from <table> where manager=name) as manager
from <table>