假设我有一个这样的表:
table_user_enrollments
username role class
John Doe student Algebra 1
Jane Duh student Algebra 1
Jeff Doh student Geometry
Jack Sprat student Algebra 1
Willie Winky student Geometry
Donald Duck teacher Algebra 1
Mickey Mouse teacher Geometry
我想要这些结果:
# of students Class name Teacher name
3 Algebra 1 Donald Duck
2 Geometry Mickey Mouse
我将如何编写查询?
(SELECT COUNT ue.username
FROM user_enrollments AS ue
WHERE ue.role="student") AS "# of Students",
ue.class AS "Class name",
(SELECT ue.username
FROM user_enrollments AS ue
WHERE ue.role="teacher") AS "Teacher name"
当然,上面的查询不起作用,但我不确定采取什么方法。
上表大大简化了。在我的现实生活中,该表是8个连接的结果。这更接近我的真实问题:
(SELECT COUNT u.username
WHERE ra.roleid='5') AS "Number of Students",
c.fullname AS "Course name",
(SELECT u.username
WHERE ra.roleid='3') AS "Teacher name"
FROM prefix_user u
JOIN prefix_user_enrolments ue on ue.userid=u.id
JOIN prefix_enrol e ON e.id=ue.enrolid
JOIN prefix_course c on c.id = e.courseid
JOIN prefix_context AS ctx ON ctx.instanceid = c.id
JOIN prefix_role_assignments AS ra ON ra.contextid = ctx.id
JOIN prefix_role AS r ON r.id = e.roleid
JOIN prefix_course_categories AS cc ON cc.id=c.category
WHERE ra.userid=u.id
GROUP BY c.id
我知道子查询在编写时不起作用,但我不知道如何正确编写它们,并且我已经包含了WHERE子句,因此您可以获得我需要的要点。
我也知道可能看起来我正在加入不必要的表,但其中一些是必要的,可以作为连接两个不共享公共列的表的桥梁。
感谢您的帮助! 金伯
答案 0 :(得分:0)
select
teachers.username,
teachers.class,
count(*) as nr_of_students
from
user_enrollments teachers
inner join user_enrollments students on
teachers.role = 'teacher' and
students.role = 'student' and
teachers.class = students.class
group by
teachers.username,
teachers.class
答案 1 :(得分:0)
试试这个
select class as [Class Name], username as [Teacher Name],
(
select count(username)
from table_user_enrollments
where role = 'student'
and class = e.class
) as [No of Student]
from table_user_enrollments e
where role = 'teacher'
答案 2 :(得分:0)
这将为您提供所需的信息:
select
count(t1.username) as "# of students",
t1.class as "class name",
t2.username as "Teacher name"
from
table_user_enrollments t1
left join
table_user_enrollments t2
on
t1.class = t2.class
where t1.role = 'student'
and t2.role = 'teacher'
group by t1.class