I think this is the logic that you want to get the date:
select itemcode,
coalesce(min(case when qty_available > 0 then date end), min(date)) as thedate
from timtest tt
where date >= date(now())
group by itemcode;
The expression coalesce(min(case when qty > 0 then date end), min(date))
seems to encapsulate your logic. The first part of the coalesce returns the first date when qty > 0
. If none of these exist, then it finds the first date with 0
. You don't state what to do when there is no record for today, but there is a record in the future for 0
. This returns the first such record.
To get the quantity, let's join back to this:
select tt.*
from timtest tt join
(select itemcode,
coalesce(min(case when qty_available > 0 then date end), min(date)) as thedate
from timtest tt
where date >= date(now())
group by itemcode
) id
on tt.itemcode = id.itemcode and tt.date = id.thedate;
EDIT:
No accounting for bad date formats. Here is a version for this situation:
select tt.*
from timtest tt join
(select itemcode,
coalesce(min(case when qty_available > 0 then thedate end), min(thedate)) as thedate
from (select tt.*, str_to_date(date, '%m/%d/%Y') as thedate
from timtest tt
) tt
where thedate >= date(now())
group by itemcode
) id
on tt.itemcode = id.itemcode and str_to_date(tt.date, '%m/%d/%Y') = id.thedate;
Advice for the future: store dates in the database as a date/datetime data time and not as strings. If you have store store them as strings, use the YYYY-MM-DD format, because you can use comparisons and order by
.