2

i've designed a organization table as per below:

Name          Supervisor     Manager
David            -            -
Josseph         David         -
Jenny           Josseph      David 
Step            Josseph      David
Mike            Josseph      David
steven          David

The Chart above explain that, David is at the highest position of the organization, Josseph and steven are report to David; Jenny, step and mike reporting to Josseph.

I would like to know how many person are reporting to David; and David is the manager to how many person? This is my expected table:

Supervisor    Manager
2            3

Can it be done with only 1 query?

3 Answers 3

3

http://sqlfiddle.com/#!9/f39ce/2

SELECT SUM(IF(Supervisor='David',1,0)),
  SUM(IF(manager='David',1,0))
FROM mytable

and here is an example of grouping query, if you ever need one:

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;
Sign up to request clarification or add additional context in comments.

2 Comments

thank you for the answer, very simple, i like it! may i know what is the meaning of '1,0' inside that query ?
since we use SUM function in query we need to summarize something :-) so when supervisor or manager equal to 'David' we increasesum +1 and when it is not equal we adding nothing +0
2

It can:

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;

This will get you something like:

BossName Supervises    Manages

David    2             3
Josseph  3             0
Jenny    0             0
....     0             0

1 Comment

don't want to downvote. but you query is not working at all. don't know who and why upvoted. sqlfiddle.com/#!9/bdd738/1
1

Use the below query

select name,(select count(*) from <table> where supervisor=name) as supervisor,
(select count(*) from <table> where manager=name) as manager    
from <table>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.