0

假设我有两张桌子。学生表和观察表。如果学生表如下所示:

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

换句话说,我想从学生表中收集每个学生的数据,并为每个学生计算观察表中 A 观察的数量,并将其附加到其他信息上。我该怎么做呢?

4

2 回答 2

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

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

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
于 2012-06-01T03:29:36.747 回答
2

您可以加入具有特定条件的表,通过这样做,您可以拥有 Observation_B_Count 和 Observation_C_Count 等字段。

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
于 2012-06-01T03:43:10.913 回答