I have a database and within this DB I have a Table called "Bakery". Within this Table there are two columns, Food and Time. The first column Food represents the food that is produce and then the second column Time represnts the time the food it was made.
Cookie 5:00 AM
Cookie 5:10 AM
Cookie 5:18 AM
Cookie 5:30 AM
John bought a cookie at 5:17 AM when was the last batch of cookies made for John?
I assume that "input" values are
BUYED_FOOD (cookie i.e.) and
TIME_OF_BUYING (5:17 i.e.).
SELECT DISTINCT ON (FOOD) * FROM Bakery WHERE FOOD = 'cookie' AND TIME < TIME_OF_BUYING ORDER BY FOOD, TIME DESC
This example is general and returns whole row from
Bakery. If you want to return only
TIME you can replace
DISTINCT part and
ORDER .. DESC with
MAX(TIME) like so :
SELECT MAX(TIME) FROM Bakery WHERE FOOD = 'cookie' AND TIME < TIME_OF_BUYING