You can use a subquery or use an INNER JOIN.
One option is to use INNER JOIN
:
SELECT id,
data,
valor
FROM teste
INNER JOIN (SELECT MAX(valor) AS valor
FROM teste
WHERE data BETWEEN '2017-03-01 00:00:00' AND
'2017-04-01 00:00:00') AS j
USING (valor)
The INNER JOIN
will take everything that is between the dates set and will return the max()
. Then, using the Valor
as a basis (in USING()
) we will take all the data that have the same value defined by MAX()
.
Another option is to simply make one valor = (SELECT ...)
, for example:
SELECT id,
data,
valor
FROM teste
WHERE valor = (SELECT MAX(valor)
FROM teste
WHERE data BETWEEN '2017-03-01 00:00:00' AND
'2017-04-01 00:00:00')
This form is easier to understand and performs the same than in the other method, first takes the maximum value (by MAX()
) and then get all the information where the valor
is equal to MAX()
.
Could explain the query?
– gato
Sort by the highest value in descending order, and take only the first result.
– Jefferson Silva