I need to return the row with the maximum timestamp grouped by the code
column but I can't seem to get it to work. I'm on MySQL 5.7. I've run queries like this before and it seemed to work in the past. Not sure what's changed or what I could be doing wrong.
mysql> CREATE TABLE test (code VARCHAR(20), timestamp DATETIME, id VARCHAR(20));
mysql> INSERT INTO test (code, timestamp, id) VALUES ('NA01M06152018','2018-06-15 21:01:00','111'),('NA01M06152018','2018-06-15 22:01:00','222'),('NA01M06152018','2018-06-15 23:01:00','333');
mysql> SELECT * FROM test;
+---------------+---------------------+------+
| code | timestamp | id |
+---------------+---------------------+------+
| NA01M06152018 | 2018-06-15 21:01:00 | 111 |
| NA01M06152018 | 2018-06-15 22:01:00 | 222 |
| NA01M06152018 | 2018-06-15 23:01:00 | 333 |
+---------------+---------------------+------+
mysql> SELECT code, MAX(timestamp), id FROM test GROUP BY code;
+---------------+---------------------+------+
| code | MAX(timestamp) | id |
+---------------+---------------------+------+
| NA01M06152018 | 2018-06-15 23:01:00 | 111 |
+---------------+---------------------+------+
I would expect the id
to be 333
because that's the row with the max timestamp but I get 111
instead which is the row with the minimum timestamp.