Take the largest value from a Mysql column

Asked

Viewed 789 times

1

I have a column where you store the values:

Nome | Turma | Nota1 | Nota2 | Nota3 | Nota4

How would I get the highest score of the Nota1, Nota2, Nota3 and Nota4 fields? I understand that MAX() does this, but how could I apply to my need?

  • 1

    Hello Fox.11, managed to solve the problem?

2 answers

2


You can use the CASE WHEN to solve your problem by performing the consultation as follows:

SELECT Nome, Turma,
CASE
       WHEN Nota1 >= Nota2 AND Nota1 >= Nota3 THEN Nota1
       WHEN Nota2 >= Nota1 AND Nota2 >= Nota3 THEN Nota2
       WHEN Nota3 >= Nota1 AND Nota3 >= Nota2 THEN Nota3
       ELSE                                        Nota4
END AS MaiorNota
FROM *suaTabela*

You can also use the GREATEST command by passing the amount of parameters to be returned the highest value, for example:

SELECT Nome, Turma, GREATEST(Nota1, Nota2, Nota3, Nota4) AS MaiorNota FROM *suaTabela*

I hope I’ve helped!

  • 1

    Hello André. Perfect! I used your first solution. Thank you very much.

  • 1

    Glad to be able to help you. Great success!

1

SELECT GREATEST(Nota1, Nota2, Nota3, Nota4) FROM tabela WHERE id=1

Browser other questions tagged

You are not signed in. Login or sign up in order to post.