Use the operator BETWEEN
to make date range queries.
Example:
SELECT *
FROM saldo
WHERE DATE(data_mov_saldo) BETWEEN DATE(dataini) AND DATE(datafin)
ORDER BY data_mov_saldo DESC
That way you can eliminate the REPEAT
.
To take the last amount of each day, do something like this:
SELECT DATE(data_mov_saldo) as data_mov_saldo, valor
FROM
(
SELECT data_mov_saldo as data_mov_saldo, valor,
(
CASE DATE(data_mov_saldo)
WHEN @curData
THEN @curRow := @curRow + 1
ELSE @curRow := 1 AND @curData := DATE(data_mov_saldo) END
) + 1 AS rn
FROM saldo, (SELECT @curRow := 0, @curData := '') r
WHERE DATE(data_mov_saldo) BETWEEN DATE('2015-06-01') AND DATE('2015-06-30')
ORDER BY data_mov_saldo DESC
) result
WHERE result.rn = 2
Explanation
First of all I need to create variables in the query that will enable me to make an equivalent to ROW_NUMBER()
next to the PARTITION BY
.
(SELECT @curRow := 0, @curData := '') r
Within the CASE
we increase the line while the date is the same day (DATE
) independent of the time. It is the @curData
which allows me to make this grouping of counters.
(
CASE DATE(data_mov_saldo)
WHEN @curData
THEN @curRow := @curRow + 1
ELSE @curRow := 1 AND @curData := DATE(data_mov_saldo) END
) + 1 AS rn
At last I command data_mov_saldo DESC
to pick up the last record of the day and on SELECT
from outside do result.rn = 2
to catch only the 1° registration of each grouping.
It is not possible, I tried this way, but several records are generated per day and I need to get only the last of each day. So I did this way.
– rodrigom
Hold on, we’ll sort it out
– Maicon Carraro
@Mamedio I updated my answer, the dates I set in between, you can change according to your parameters.
– Maicon Carraro
I also put explanations :)
– Maicon Carraro
Man, I couldn’t understand... The process already brings the last record of each day, the repeat is to run between dates, I could not implement here your answer :s
– rodrigom
@Mamedio Com o
select
that I showed you you only run it once, you don’t need the repeat. As you want to display the final result?– Maicon Carraro
Man, GREAT, I’m getting here, you saved my skin hehehehe Thank you so much, I’ll make it cute and give you a return!
– rodrigom
Let’s go continue this discussion in chat.
– rodrigom