Although this question looks simple, it is kind of tricky.
I have a table with the following columns:
table A:
int ID
float value
datetime date
varchar(50) group
I would like to obtain the "ID" and "value" of the records that contain the maximum "date" grouped by the column "group". Something like "what is the newest value for each group?"
I can get each group and its maximum date:
SELECT group, MAX(date) FROM A GROUP BY group; -- I also need the "ID" and "value"
But I would like to have the "ID" and value of the record with the highest date.
Making a JOIN between A and the result could be the answer, but there is no way of knowing which record MAX(date) refers to (in case the "date" repeats).
Can someone help?
As long as the Date column is unique for each group I think something like this might work:
You could try with a subquery
This is just what analytic functions were made for:
If date is unique, then you already have your answer. If date is not unique, then you need some other uniqueifier. Absent a natural key, your ID is as good as any. Just put a MAX (or MIN, whichever you prefer) on it: