如何组合不同查询的输出。
我有以下带有输出的sql查询:
1) select d.departmentid, d.name, count(distinct(sg.personid)) as noOfStudents 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;
+--------------+--------------+--------------+
| departmentid | name | noofstudents |
+==============+==============+==============+
| 101 | Computer Sci | 1 |
| 104 | Mech | 2 |
| 103 | EEE | 1 |
+--------------+--------------+--------------+
2) select d.departmentid, d.name, count(distinct(ci.personid)) as noOfTeachers 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;
+--------------+--------------+--------------+
| departmentid | name | noofteachers |
+==============+==============+==============+
| 101 | Computer Sci | 1 |
| 103 | EEE | 2 |
| 104 | Mech | 1 |
| 102 | ECE | 3 |
+--------------+--------------+--------------+
3) select d.departmentid, d.name, 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 | noofcourses |
+==============+==============+=============+
| 101 | Computer Sci | 3 |
| 102 | ECE | 3 |
| 104 | Mech | 1 |
| 103 | EEE | 2 |
+--------------+--------------+-------------+
现在我想把这三个合并到一个表中来显示数据。我该怎么做?
我在这里尝试联合行动,它好用吗?
2条答案
按热度按时间plicqrtu1#
可以使用内部联接来获取同一行上的所有结果
或者,如果需要分隔行的结果,可以使用union all
pbwdgjma2#
如果需要在输出中将学生、教师和课程作为单独的列,可以尝试以下操作:
这应该会产生这样的结果:
如果需要聚合值,只需将整个查询括在括号中,然后对结果求和