我使用以下代码加入了三个表CC,学生和教师:
SELECT CC.Course_number , CC.Expression, teachers.Lastfirst, students.gender, teachers.sched_department
From CC
inner join students ON CC.StudentID=students.ID
inner join teachers ON CC.TeacherID=Teachers.ID
Where CC.SchoolID=151 and CC.TermID=2401
Order by teachers.sched_department, CC.course_number, Teachers.Lastfirst, CC.Expression, students.gender
代码适用于我获得包含课程代码,课程期限,教师姓名,部门和性别的列表。
然而,我希望的输出是一种浓缩格式,如下所示:
来自CC表的 Course Number
(一次),来自CC表的Course Expression
,来自教师表的Teacher
,来自教师表的Department
,Male
来自学生表的学生表{(1}}(在该特定班级中计算)的特定班级。
我试过的最后一个代码是:
Female
任何建议都会很棒。
答案 0 :(得分:0)
在不知道表格结构和样本输入/输出数据的情况下,您很难确切地知道您正在寻找什么,但也许这就是您想要的?如果不是,请澄清您的要求并添加样本数据。
SELECT
CC.Course_number,
CC.Expression,
Teachers.Lastfirst,
Teachers.sched_department,
SUM(students.gender = 'male') AS males,
SUM(students.gender = 'female') AS females
FROM CC
INNER JOIN Students ON CC.StudentID = students.ID
INNER JOIN Teachers ON CC.TeacherID = Teachers.ID
WHERE CC.SchoolID = 151 and CC.TermID = 2401
GROUP BY
CC.Course_number,
CC.Expression,
Teachers.Lastfirst,
Teachers.sched_department
ORDER BY
teachers.sched_department,
CC.course_number,
Teachers.Lastfirst,
CC.Expression
Sample SQL Fiddle(对表格结构有很多假设......)