You could loop, incrementing the search date, until something come back, but there are probably better ways to either improve the SQL or pull more data than you want and process the search in Node-RED.
The main entity state table holds every state change event, so if an entity goes ‘unavailable’ then that will appear as the state value at that time. There are no time gaps in the state value, hence we see ‘unavailable / unknown’ “holes” in the entity-state history.
The statistics tables, both sort and long-term, take a snapshot of the statistics of the entity state value over five minutes and over one hour. The statistics ‘entity state’ value in the long-term statistics is (if I understand this correctly) the average or sum of the entity state over the full hour, and this will therefore capture a value where there was at least one real state value during the hour period. In your graph example above, there will be a long-term ‘state’ value for 6:00, 7:00 and 8:00 as the gap does not span a full one hour period. The statistics entry will only not exist if the base entity state was unavailable for the entire hour.
In most cases you can just use SQL to request the exact entry at, say, “2024-10-15” and “18:00” and expect to get something. It is not difficult to expand this to cover the full day, so all of “2024-10-15” and then to order and group by time, so that you can pick the last entry of the day. This will deal with, for example, where the sensor went off-line at 12:00 and there is no 18:00, but there is a record for 11:00.
If you don’t want to do all the work in the SQL statement, then it is very easy to pull, for example, an entire year of data. Since the long-term stats table holds only 24 records per day, that is an array of around 9000 items for a year, and it is not difficult to then use Node-RED and either JS or JSONata to process the array there.
If I wanted to do your example, I would execute an SQL statement to pull an entire year (or even the entire data set) grouped by day, so I get one end-of-day odometer figure per day, then use JSONata to knock this into shape. From there I would take the date of interest and return either the exact match from the date-odometer array, or find the first entry in the date following.