2012-06-01 3 views
0

두 테이블이 있다고 가정 해 봅시다. 학생 표와 관측 표. 학생들 테이블처럼 보이는 경우SQL - 특정 값으로 다른 테이블의 링크 된 항목을 계산하는 방법

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

그리고 관찰 테이블 보이는 같은 :

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

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 

기본적으로, 쿼리에서 원하는 결과는 다음과 같은 것

즉, students 테이블의 각 학생에 대한 데이터를 수집하고 각 학생 수에 대한 관측 테이블에서 얻은 관측 수를 다른 데이터로 집계하고 싶습니다. 어떻게해야합니까?

감사합니다.

+0

항상 어떤 데이터베이스를 사용해야하는지 SQL dialects로 노래 부르십시오. 숙제를하고 실제 질문을하지 않을 때 숙제로 질문에 태그를 붙여야합니다. – mattmc3

답변

4

이것은 간단한 가입 집계입니다 :

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

을, 당신이 할 수있는이 작업을 수행하여 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 
관련 문제