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

时间:2012-06-01 03:23:09

标签: 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  4          B
9  1          A

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

Student Grade Observation_A_Count
Alex    3     2
Barney  3     1
Cara    4     2
Diana   4     0

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

2 个答案:

答案 0 :(得分:5)

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

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

答案 1 :(得分: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