Sql 如何计算另一个表中具有特定值的链接项
假设我有两张桌子。学生表和观察表。如果学生表如下所示:Sql 如何计算另一个表中具有特定值的链接项,sql,join,Sql,Join,假设我有两张桌子。学生表和观察表。如果学生表如下所示: Id Student Grade 1 Alex 3 2 Barney 3 3 Cara 4 4 Diana 4 Id Student_Id Observation_Type 1 1 A 2 1 B 3 3 A 4 2 A 5 4 B 6 3 A 7 2 B 8
Id Student Grade
1 Alex 3
2 Barney 3
3 Cara 4
4 Diana 4
Id Student_Id Observation_Type
1 1 A
2 1 B
3 3 A
4 2 A
5 4 B
6 3 A
7 2 B
8 4 B
9 1 A
观察表如下所示:
Id Student Grade
1 Alex 3
2 Barney 3
3 Cara 4
4 Diana 4
Id Student_Id Observation_Type
1 1 A
2 1 B
3 3 A
4 2 A
5 4 B
6 3 A
7 2 B
8 4 B
9 1 A
基本上,我希望查询的结果如下:
Student Grade Observation_A_Count
Alex 3 2
Barney 3 1
Cara 4 2
Diana 4 0
换句话说,我想从students表中为每个学生收集数据,并为每个学生计算观察表中的观察次数,并将其添加到其他信息中。如何进行此操作?这是一个简单的联接和聚合:
select
a.Student,
a.Grade,
count(b.Id) as Observation_A_Count
from
Student a left join
Observations b on a.Id = b.Student_Id
group by
a.Student,
a.Grade
order by
1
或者,您可以使用相关子查询:
select
a.Student,
a.Grade,
(select count(*) from observations x where x.Student_Id = a.Id) as Observation_A_Count
from
Student a
order by
a.Student
您可以将表与特定条件联接,通过这样做,您可以有一个字段用于观察\ B \ u计数和观察\ C \ u计数等
SELECT Student.Student, Student.Grade, COUNT(Observation_Type.*) AS Observation_A_Count
FROM Student
LEFT JOIN Observations ON Observations.Student_ID = Student.Student_ID AND Observations.Observation_Type = 'A'
GROUP BY Student.Student, Student.Grade
由于SQL方言不同,您应该始终指定要使用的数据库,并且在做作业而不是问真实世界的问题时,还应该确保将问题标记为家庭作业。