2016-09-21 3 views
1

students, template_subjectssubjects 3 개의 테이블을 쿼리하려고합니다.두 번째 학위의 열 합계가 합류합니까?

studentstemplate_subjects 테이블이 template_code 열이, 그래서 나는 template_codes 테이블과 subjects 테이블 사이의 피벗 테이블이 생각이 열 (을 통해 가입 할 수 있습니다. 이것은 단지 쿼리, 내가 설계 데이터베이스 아니다 지금).

이제 테이블의 units 테이블의 합계를 template_code으로 그룹화해야합니다. 내가 어떻게 해? 내가 쿼리에서 얻을수 있다고 기대하는 것은 예를 들어,

SELECT 
s.studNo as 'Student Number', 
s.lastName as 'Student Name', 
s.template_code as 'Template Code', 
(SELECT sum(units) FROM subjects 
JOIN template_subjects ON subjects.subject_code=template_subjects.subject_code 
GROUP BY s.template_code) as 'Units' 
FROM students as s 
JOIN template_subjects ON template_subjects.template_code=s.template_code 

입니다

: 여기

는 지금까지 시도했습니다 무엇 Units은 내부 과목의 총 단위입니다

Student Number | Student Name | Template Code | Units 
201555101  Jane Doe  ACC301   35 

특정 템플릿 코드. (테이블 이름과 열은 훨씬 복잡한 이름을 가지고 있으므로이 질문에서 간단하게 설명했습니다.이 질문에서 작성한 오류나 혼동스러운 부분을 알려주십시오.)

+1

학생 번호 = 학생 번호 및 학생 이름 = 201555101 – tomb

답변

1

, 여기에 내가 그것을 작동하게하는 방법이다 또한 하위 쿼리에서 subjects 테이블 자체를 쿼리하는 대신를 쿼리했습니다. 대신 3230을 입력하고 subjects 테이블에 조인하십시오.

1

나는 다음과 같이하고 싶습니다.

SELECT s.studNo as `Student Number`, s.lastName as `Student Name`, 
     s.template_code as `Template Code`, 
     (SELECT sum(ts.units) 
     FROM template_subjects ts 
     WHERE s.subject_code = ts.subject_code 
     ) as Units 
FROM students s; 

즉, 상관 관계가있는 하위 쿼리가 필요하며 너무 많은 조인이 필요하지 않습니다.

WHERE template_subjects.templade_code=s.template_code 

대신 :

GROUP BY s.template_code 

SELECT 
s.studNo as 'Student Number', 
s.lastName as 'Student Name', 
s.template_code as 'Template Code', 
(SELECT sum(units) 
FROM template_subjects 
JOIN subjects ON template_subjects.subject_code=subjects.subject_code 
WHERE template_subjects.templade_code=s.template_code) as 'Units' 
FROM students as s 
JOIN template_subjects ON template_subjects.template_code=s.template_code 

은 하위 쿼리의 차이를주의 : 사람이 대답을 필요로하는 경우

+0

안녕하세요, 혼란 스럽습니다. 'template_subjects'는 단위 열을 가지고 있지 않습니다, 그것은'subjects' 테이블에 있습니다. 그래서 나는 학생을 template_subject에 연결할 수 있고 template_subject는 subject_code에 기반하여 주제에 연결할 수 있습니다. – christianleroy

관련 문제