Use the BETWEEN
operator to do date range queries.
Example:
SELECT *
FROM saldo
WHERE DATE(data_mov_saldo) BETWEEN DATE(dataini) AND DATE(datafin)
ORDER BY data_mov_saldo DESC
This way you can eliminate REPEAT
.
To get the last value 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 of ROW_NUMBER()
next to PARTITION BY
.
(SELECT @curRow := 0, @curData := '') r
Within CASE
we will increment the row while the date is on the same day ( DATE
) regardless of time. It is the @curData
that allows me to do 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
Finally I order data_mov_saldo DESC
to get the last record of the day and in the SELECT
outside I result.rn = 2
to get only the 1st record of each grouping.