Если вам нужно получить студентов , преподавателей и курсов в виде отдельных столбцов в выходных данных, вы можете попробовать что-то вроде этого:
select
d.departmentid, d.name,
count(distinct(sg.personid)) as noOfStudents,
0 as noofteachers, 0 as noofcourses
from
department d
inner join
course c on c.departmentid = d.departmentid
inner join
student_grade sg on sg.courseid = c.courseid
group by
d.departmentid, d.name
UNION ALL
select
d.departmentid, d.name, 0 as noOfStudents,
count(distinct(ci.personid)) as noOfTeachers, 0 as noofcourses
from
department d
inner join
course c on c.departmentid = d.departmentid
inner join
course_instructor ci on ci.courseid = c.courseid
group by
d.departmentid, d.name
UNION ALL
select
d.departmentid, d.name, 0 as noOfStudents,
0 as noofteachers, count(distinct(c.courseid)) as noOfCourses
from
department d
inner join
course c on c.departmentid = d.departmentid
group by
d.departmentid, d.name
Это должно привести к примерно так:
+--------------+--------------+--------------+--------------+--------------+
| departmentid | name | noofstudents | noofteachers | noofcourses |
+==============+==============+==============+==============+==============+
| 101 | Computer Sci | 1| 0| 0|
| 104 | Mech | 2| 0| 0|
| 103 | EEE | 1| 0| 0|
| 101 | Computer Sci | 0| 1| 0|
| 103 | EEE | 0| 2| 0|
| 104 | Mech | 0| 1| 0|
| 102 | ECE | 0| 3| 0|
| 101 | Computer Sci | 0| 0| 3|
| 102 | ECE | 0| 0| 3|
| 104 | Mech | 0| 0| 1|
| 103 | EEE | 0| 0| 2|
+--------------+--------------+--------------+--------------+--------------+
Если вам нужны агрегированные значения, просто заключите весь запрос в скобки и суммируйте результаты
SELECT
departmentid, name,
SUM(noOfStudents), SUM(noOfTeachers), SUM(noOfCourses)
FROM
(Query1 UNION ALL Query2 UNION ALL Query3) AS mySubQuery
GROUP BY
departmentid, name