Inner Join Database

0

I'm using this command in sqlserver:

SELECT ALUNOS.NOME, DISCIPLINAS.NOME AS DISCIPLINA, MAX(NOTAS.NOTA) AS MEDIA FROM NOTAS
INNER JOIN ALUNO_DISCIPLINA ON ALUNO_DISCIPLINA.identificacao = NOTAS.codAlunoDisciplina
INNER JOIN DISCIPLINAS ON ALUNO_DISCIPLINA.CODIGO_DISCIPLINA = DISCIPLINAS.CODIGO
INNER JOIN ALUNOS ON ALUNO_DISCIPLINA.registro_aluno = ALUNOS.Registro
GROUP BY DISCIPLINAS.NOME,ALUNOS.NOME
ORDER BY DISCIPLINAS.NOME

Then the result generates the following table according to the image

I would like you to show only (MARIA geography 9.00) and (JOÃO portugues 10,00), which are the highest grades of students, ie compare between Portuguese and show the highest grade tbm. Any suggestions where I'm wrong ??

    
asked by anonymous 18.06.2017 / 20:18

2 answers

0

In order to do what you need, you can use the RANK function like this:

WITH resumo AS (SELECT
                    A.Nome NomeAluno,
                    D.Nome NomeDisciplina,
                    MAX(N.Nota) MaiorNota,
                    RANK() OVER (PARTITION BY D.Nome ORDER BY MAX(N.Nota) DESC)  Posicao
                FROM ALUNOS A
                    INNER JOIN ALUNO_DISCIPLINA AD ON (A.Registro = AD.registro_aluno)
                    INNER JOIN DISCIPLINAS D ON (AD.CODIGO_DISCIPLINA = D.CODIGO)
                    INNER JOIN NOTAS N ON (AD.identificacao = N.codAlunoDisciplina)
                GROUP BY
                    A.Nome,
                    D.Nome)

SELECT 
    r.NomeAluno,
    r.NomeDisciplina,
    r.MaiorNota
FROM 
    resumo r 
WHERE 
    r.Posicao = 1
ORDER BY
    r.NomeDisciplina,
    r.NomeAluno;

The PARTITION BY divides the data by the name of the subject and ORDER BY DESC orders the highest note to the lowest, so if there are same notes for different students in the same subject, all the students will appear. The WITH is for you can name a result and then use it as I did.

References:

RANK (Transact-SQL)
WITH common_table_expression (Transact-SQL)

    
18.06.2017 / 22:38
0

I do not know how to test here, but I believe that what you need is a subquery, SELECT FROM SELECT , test there and tell me if it works (you might have to do some adjustment):

SELECT NOME, DISCIPLINA, MAX(MEDIA) AS MEDIA FROM 
    (SELECT ALUNOS.NOME, DISCIPLINAS.NOME AS DISCIPLINA, MAX(NOTAS.NOTA) AS MEDIA FROM
        NOTAS
        INNER JOIN ALUNO_DISCIPLINA ON ALUNO_DISCIPLINA.identificacao = NOTAS.codAlunoDisciplina
        INNER JOIN DISCIPLINAS ON ALUNO_DISCIPLINA.CODIGO_DISCIPLINA = DISCIPLINAS.CODIGO
        INNER JOIN ALUNOS ON ALUNO_DISCIPLINA.registro_aluno = ALUNOS.Registro
        GROUP BY DISCIPLINAS.NOME,ALUNOS.NOME
        ORDER BY DISCIPLINAS.NOME) 
GROUP BY DISCIPLINA
    
18.06.2017 / 21:11