I have this stockmoves table :
id serial op_date from to
23 aaa1 2014-11-10 0 8
24 aaa2 2014-11-10 0 8
25 aaa3 2014-11-10 0 8
26 aaa1 2014-11-18 8 1
27 aaa2 2014-11-15 8 9
28 aaa2 2014-11-19 9 8
29 aaa2 2014-11-20 8 10
(Please ignore the column names, I shortened them to be more succinct just for posting here even if they might be reserved sql names.)
And I want to extract a unique list of serials with the latest date they have for a certain "to" (location where the product's sent). If I do:
SELECT serial, MAX(op_date) as max_op_date
FROM stockmoves
WHERE to = 8
GROUP BY serial;
I get the expected (good) answer:
serial max_op_date
aaa1 2014-11-10
aaa2 2014-11-19
aaa3 2014-11-10
However, if I add in the results the "from" column, like this:
SELECT serial, from, MAX(op_date) as max_op_date
FROM stockmoves
WHERE to = 8
GROUP BY serial;
I get an incorrect answer for serial aaa2 imho:
serial from max_op_date
aaa1 0 2014-11-10
aaa2 0 2014-11-19
aaa3 0 2014-11-10
instead of the expected:
serial from max_op_date
aaa1 0 2014-11-10
aaa2 9 2014-11-19
aaa3 0 2014-11-10
Am I missing something or my old version of MySQL (I am forced to use) has a problem? Shouldn't correspond the "from" value to the line that has the max(op_date) value?
Thank you in advance,
Lian
EDIT:
Ok, following suggestions here is a more complex statement that does what I need:
SELECT sm1.serial, sm1.op_date, sm1.from
FROM stockmoves sm1
JOIN (
SELECT serial, max(id) as max_id
FROM stockmoves
WHERE to = 8
GROUP BY serial
) sm2 ON (sm2.max_id = sm1.id)
Thank you!!!