如何计算具有特定值的另一个表中的链接条目

Jen*_*ars 0 sql join

假设我有两张桌子.学生表和观察表.如果学生表看起来像:

Id Student Grade
1  Alex    3
2  Barney  3
3  Cara    4
4  Diana   4
Run Code Online (Sandbox Code Playgroud)

观察表看起来像:

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
Run Code Online (Sandbox Code Playgroud)

基本上,我从查询中得到的结果如下:

Student Grade Observation_A_Count
Alex    3     2
Barney  3     1
Cara    4     2
Diana   4     0
Run Code Online (Sandbox Code Playgroud)

换句话说,我想从学生表中收集每个学生的数据,并为每个学生计算观察表中A观察的数量,并将其与其他信息相关联.我该怎么做呢?

mat*_*mc3 6

这是一个简单的连接和聚合:

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
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用相关子查询:

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
Run Code Online (Sandbox Code Playgroud)