Similar question had been ask multiple times, but none of the answers help in this situation, so asking the question again
I have a table with this following structure(yeah no unique key here):
---------------------------------------------------------------
|a_number | a_status | b_status | ref_id | timepublished |
|(text) | (text) | (text) |(text) | (datetime) |
---------------------------------------------------------------
|1 | U | U | re1 | 2016-08-12 13:24:25 |
|1 | P | U | re1 | 2016-08-12 13:24:35 |
|1 | P | P | re1 | 2016-08-12 13:24:45 |
|2 | U | U | re2 | 2016-08-12 12:24:30 |
|2 | U | F | re1 | 2016-08-12 12:24:45 |
|4 | U | U | re3 | 2016-08-12 13:24:30 |
|4 | U | U | re4 | 2016-08-13 15:24:30 |
---------------------------------------------------------------
Now the problem I am trying to solve is to get the latest states for each a_number. So the CORRECT output should be:
---------------------------------------------------------------
|1 | P | P | re1 | 2016-08-12 13:24:45 |
|2 | U | F | re1 | 2016-08-12 12:24:45 |
|4 | U | U | re3 | 2016-08-12 13:24:30 |
|4 | U | U | re4 | 2016-08-13 15:24:30 |
---------------------------------------------------------------
And the query I have is :
SELECT af.a_number
, af.a_status
, af.b_status
, af.ref_id
, af.timepublished
FROM af_biz af
JOIN
(SELECT MAX(timepublished) timepublished, ref_id
FROM af_biz GROUP BY ref_id) tmp
ON tmp.timepublished = af.timepublished AND tmp.ref_id = af.ref_id
ORDER BY af.a_number;
But the result I get contain incorrect output like this (Notice that the time is max timepublished but statuses are different):
---------------------------------------------------------------
|1 | P | U | re1 | 2016-08-12 13:24:45 |
|1 | P | P | re1 | 2016-08-12 13:24:45 |
|2 | U | U | re2 | 2016-08-12 12:24:45 |
|2 | U | F | re1 | 2016-08-12 12:24:45 |
|4 | U | U | re3 | 2016-08-12 13:24:30 |
|4 | U | U | re4 | 2016-08-13 15:24:30 |
---------------------------------------------------------------
Anyone has any idea on what could be wrong with my query ??
GROUP BY af.a_numbergroup by... you should include all columns present in select list to group by and not only a specific column. That's what the comments points put.