3
I have the following tables below, where schemes(columns) are described in parentheses and the primary key appears in bold:
pupil(codpupil, named, dt_ticket, codcurso)
course(codcurso, naming)
registration(codpupil, codturma, media, result)
gang(codturma, periodolent, room, codprof, coddisc)
discipline(coddisc, title, credits)
teacher(codprof, teacher name, degree)
I wish to perform the following sql query:
What was the name, the average grade (considering the averages of all the disciplines in which you enrolled) and the total credit obtained by each student? Remember that a student only gets credits in a discipline if he or she passes this class.
I already got the following sql expression:
SELECT nomealuno, sum(media)/count(codaluno) FROM aluno
NATURAL JOIN matricula GROUP BY aluno.codaluno;
Where are listed the names of the students and their respective media, but still have to obtain the total credits and still perform the condition "only get credits in a discipline if you pass this discipline". How to complement my sql query to get the remaining requirements above?
Relationship as requested in the comments:
Note: These arrows indicate the foreign keys that were imported.
@gmsantos sim matrícula(codaluno, codturma, media, resultado) está na coluna resultado... que é o resultado da matrícula se o estudante foi aprovado ou não.
– Pedro Rangel
What is the type of data in this result column? It says if the student has passed the course, is it? Is it a boolean? 0/1?
– bfavaretto
@bfavaretto yes
– Pedro Rangel
Try :
SELECT aluno.nomealuno, sum(matricula.media)/count(aluno.codaluno), sum(disciplina.creditos) FROM aluno, matricula, disciplina, turma WHERE aluno.codaluno = matricula.codaluno AND matricula.codturma = turma.codturma AND turma.coddisc = disciplina.coddisc GROUP BY aluno.codaluno;
.– Cold
And I suggest:
SELECT a.nomealuno, AVG(m.media), SUM(IF(m.resultado=1, d.creditos, 0)) FROM aluno a 
LEFT JOIN matricula m ON a.codaluno = m.codaluno 
LEFT JOIN turma t ON m.codturma = t.codturma 
LEFT JOIN disciplina d ON t.coddisc = d.coddisc 
GROUP BY a.codaluno
I have no bench to test– wryel
@Pedrorangel You can test with more fake data by editing the SQL Fiddle I created: http://sqlfiddle.com/#! 2/d8755/5
– bfavaretto