-1
I have the table "saldo_dia" where I record the product (ID), the date and the balance. I need to generate a report (Kardex) and fetch the balance of a given day as "starting balance".
My question is the following: if the user searches from a date that the product did not have movement (that is, there is no "saldo_dia" for that date), I am looking for the next day with balance. However, it may be that there is no "next day", in this case - and I think it is the right one - it would be to look for the last day with balance. But how to do this without generating unnecessary additional queries?
Example:
The reporting period is from 01/12/2019 to 10/12/2019. The last "saldo_dia" was 25/11/2019 and the next "saldo_dia" was only 05/12/2019.
Which "day balance" should I display as the starting balance? And how to correctly search for this balance?
EDIT
The consultation I am currently carrying out is as follows::
SELECT SaldoDia.saldo FROM saldo_dias AS SaldoDia WHERE SaldoDia.produto_id = 1 AND SaldoDia.dia >= '2019-12-01' LIMIT 1
The informed date is the initial date of the requested report.
Do the following, create an IF in your code, if it does not find anything at the current date, limit a number of days for it to find results, example, 7 days and mount a new query inside the if, one for 7 days more and another for 7 days less, can leave this number for the client’s choice when generating the report...
select * FROM tabela WHERE saldo_dia BETWEEN concat(CURRENT_DATE(), ' 00:00:00') AND concat(CURRENT_DATE() + INTERVAL 7 DAY, ' 23:59:59')
, this helps you?– Jakson Fischer
@Jaksonfischer this is basically the consultation I already do today. What I’m trying to avoid is just keep creating IF’s. In addition there is the question of a given product may not have had movement (and therefore without "saldo_dia") in a period of 7 days, for example.
– Danilo Miguel
And why not report that there are no results for this interval?
– Jorge B.
@Jorgeb. is that you may have movement in the reported interval. What you may not have is a "saldo_dia" coinciding with the initial day of the report. For example, as I mentioned above: the report starts on 01/12/2019, but the last "saldo_dia" is only on 25/11/2019. That is, it has movement, but does not have the "saldo_dia" from the beginning of the report. In this case, I have to take the balance closer to the beginning of the report.
– Danilo Miguel
But isn’t the initial balance always the balance of the day immediately prior to the requested period in which a movement took place? In this case it is not sufficient to take the balance of the longest <= starting date of the period or, if no such movement exists, consider the zero balance?
– anonimo
@anonymity makes sense. I hadn’t thought of it that way and I think I was complicating things a bit here. I’m going to test this and I think it will work.
– Danilo Miguel