I need to select the maximum amounts in one column for a common id in another column. There could be several id's in the report_id column that have the same, maximum last_update amounts.
Data structure:
+------+-------+--------------------------------------------+
| id | report_id | last_update |
+------+-------------+--------------------------------------+
| 1 | 1 | 2019-01-24 |
| 2 | 1 | 2019-01-24 |
| 3 | 1 | 2019-01-24 |
| 4 | 2 | 2019-01-24 |
| 5 | 3 | 2019-01-23 |
+------+-------+--------------------------------------------+
The problem I am having so far is I can't seem to isolate my results simply by the report_id. For example, with the following query:
"SELECT report_id, last_update
FROM reports
WHERE last_update=(
SELECT MAX(last_update) FROM reports
WHERE report_id='1'
);
";
This returns:
+------+-------+--------------------------------------------+
| id | report_id | last_update |
+------+-------------+--------------------------------------+
| 1 | 1 | 2019-01-24 |
| 2 | 1 | 2019-01-24 |
| 3 | 1 | 2019-01-24 |
| 4 | 2 | 2019-01-24 |
+------+-------+--------------------------------------------+
So it is nearly correct, but it also is including report_id 2 because it also has the MAX value of 2019-01-24 in last_update.
What I really need to do is select all columns with report_id as 1, and then select only the rows from that result set with MAX(last_update) but I have been looking at every greatest-nth-per-group and associated question on SO and I just can't get this one.
Anytime I bring MAX into the query it seems to negate the fact I am trying to isolate by report_id as well.