Although this question looks simple, it is kind of tricky.
Consider the following table:
CREATE TABLE A (
id INT,
value FLOAT,
"date" DATETIME,
group VARCHAR(50)
);
I would like to obtain the ID
and value
of the records that contain the maximum date
grouped by the column group
. In other words, something like "what is the newest value for each group?" What query will answer that question?
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).
Sample data:
INSERT INTO A
VALUES
(1, 1.0, '2000-01-01', 'A'),
(2, 2.0, '2000-01-02', 'A'),
(3, 3.0, '2000-01-01', 'B'),
(4, 2.0, '2000-01-02', 'B'),
(5, 1.0, '2000-01-02', 'B')
;