0

I'm having huge difficulty with a 3 table query.

The scenario is that TEAM has many or no MEMBERS, a MEMBER could have many or no TASKS. What I want to get is the number of TASKS for every TEAM. TEAM has its own ID, MEMBER holds this as a FK on TEAM_ID, TASK has MEMBER_ID on the TASK.

I want to get a report of TEAM.NAME, COUNT(Person/Team), Count(Tasks/Team)

I have myself so confused, My thinking was to use an Outer Join on TEAM and MEMBER so I have all the teams with any members they have. From here I'm getting totally confused. If anyone can just point me in the right direction so I have something to work from I'd be so greateful

Strawberry
  • 33,750
  • 13
  • 40
  • 57
  • If you provide samples of tables and expected result table that would hel a lot! :-) – Alex Jan 31 '15 at 02:01

3 Answers3

1

I think you can do what you want with aggregation -- and count(distinct):

select t.name,
       count(distinct m.memberid) as nummembers,
       count(distinct tk.taskid) as numtasks
from team t left join
     member m
     on t.teamid = j.teamid left join
     tasks tk
     on tk.memberid = m.memberid
group by t.name;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
1

Try this out :

SELECT Team.name, COUNT(Person.id_person), COUNT(Tasks.id_task)
FROM Team t,
LEFT JOIN Person p on p.team_id = t.id_team
LEFT JOIN Tasks ts on ts.person_id = p.id_person
GROUP BY p.team_id, ts.person_id
JC Sama
  • 2,214
  • 1
  • 13
  • 13
1

You want to use count distinct:

MySQL COUNT DISTINCT

select t.name as Team,
    count(distinct m.ID) as Member_cnt,
    count(distinct t.ID) as Task_cnt
from team t
   left join member m
       on t.ID= m.TEAM_ID
   left join tasks t
     on t.MEMBER_ID= m.ID
group by t.name;
Community
  • 1
  • 1
Ron Smith
  • 3,241
  • 1
  • 13
  • 16
  • 1
    Thanks! I had got as far as the left joins previously, I was missing the group by and count distinct instead of the plain count! – user3240957 Jan 31 '15 at 12:04