简体   繁体   中英

How to count linked entries in another table with a specific value

Let's say I have two tables. A students table and an observations table. If the students table looks like:

Id Student Grade
1  Alex    3
2  Barney  3
3  Cara    4
4  Diana   4

And the observations table looks like:

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

Basically, the result I'd like from the query would be the following:

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

In other words, I'd like to gather data for each student from the students table and for each student count the number of A observations from the observations table and tack that onto the other information. How do I go about doing this?

This is a simple join and aggregate:

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

Or, you can use a correlated subquery:

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

You can join the table with a specific condition, by doing this you can have a field for Observation_B_Count and Observation_C_Count, etc.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM