问题
I'm sorry I can't be more specific, but I don't know how to describe my problem in the title.. respectively I don't know how to search for similar question.
So here is the deal. I have this table with records:

As you can see, I have data, entered on different months with different type. My goal is to get the last entered amount grouped by type and this should be limited by date.
For example:
If I specify a date 2011-03-01, the query should return 3 records with amount - 10, 20 and 30, because for type=1 the nearest inserted record to '2011-03-01' is on date 2011-01-01 with amount 10. For type=2 the nearest date to '2011-03-01' is 2011-02-01 with amount 20. And for type=3 the nearest to '2011-03-01' is the '2011-03-01' so it returns amount=30.
So how to form the MySQL query?
回答1:
Right now I can only think of a subselect version:
SELECT type, amount
FROM table AS t
WHERE dat = (
SELECT MAX(dat)
FROM table
WHERE type=t.type
AND dat <= '2011-03-01'
)
来源:https://stackoverflow.com/questions/5565360/get-nearest-records-to-specific-date-grouped-by-type