如果我们有以下两个表,“教师”和“类”,我们如何使用INNER JOIN语句来生成最终表
“老师”表
teachers
class_id teacher_id teacher_name class_count
1111 1234 Smith 2
1111 2345 Jones 4
2222 1234 Smith 2
2222 2345 Jones 4
1111 5678 Taylor 2
3333 2345 Jones 4
4444 5678 Taylor 2
4444 2345 Jones 4
“班级”表
classes
id class_name rating
1111 Math 60
2222 Biology 70
3333 Psychology 50
4444 Physics 80
5555 Chemistry 30
6666 Economics 60
7777 Computing 70
8888 Statistics 90
我们希望决赛桌看起来像:
teacher1_id teacher2_id pair_count average_teacher_rating
1234 2345 2 65
2345 5678 2 70
我在sqlite中尝试了以下代码,但它没有给出所需的结果(如上面的最终表中所示)。
SELECT
t.teacher1_id
, t.teacher2_id
, COUNT(t.teacher1_id = t.teacher2_id)
, (c.rating1 + c.rating2) / COUNT(t.teacher1_id = t.teacher2_id)
FROM teachers t
INNER JOIN classes c on c.id = t.class_id
WHERE COUNT(t.teacher1_id = t.teacher2_id) > 1;
尝试:
select
t1.teacher_id as t1
, t2.teacher_id as t2
, count()
, avg(c.rating)
from teachers t1 inner join teachers as t2
on t1.class_id = t2.class_id and t1.teacher_id < t2.teacher_id
left join classes c on c.id = t1.class_id
group by t1, t2
having count()>1;
我相信以下内容可能符合您的要求: -
WITH cte1 AS
(
SELECT
t1.teacher_id AS teacher1_id,
t1.teacher_name AS t1name,
t2.teacher_id AS teacher2_id,
t2.teacher_name AS t2name,
c.class_name,
avg(c.rating) AS average_teacher_rating,
count(c.class_name) AS pair_count
FROM teachers AS t1
LEFT JOIN classes AS c ON t1.class_id = c.id
INNER JOIN teachers AS t2 ON t1.class_id = t2.class_id AND t1.teacher_id < t2.teacher_id
GROUP BY teacher1_id,teacher2_id
HAVING pair_count > 1
)
SELECT teacher1_id, teacher2_id, pair_count, average_teacher_rating FROM cte1
;
这导致: -
即它可能是: -
SELECT
t1.teacher_id AS teacher1_id,
t2.teacher_id AS teacher2_id,
avg(c.rating) AS average_teacher_rating,
count(c.class_name) AS pair_count
FROM teachers AS t1
JOIN teachers AS t2 ON t1.class_id = t2.class_id AND t1.teacher_id < t2.teacher_id
JOIN classes AS c ON t1.class_id = c.id
GROUP BY teacher1_id,teacher2_id
HAVING pair_count > 1
;