I have table like this
id | serial_num | version | .....
1 | 1 | 1 | .....
2 | 2
Selecting id
for a group by query is useless. You should only select the column you are using in group by and other columns that are being applied aggregate functions.
Hope this works for you.
SELECT id,
serial_num,
Max(`version`) `version`
FROM tbl1
GROUP BY serial_num
Try this:
SELECT yourtable.*
FROM yourtable
WHERE (serial_num, version) in (select serial_num, max(version)
from yourtable
group by serial_num)
Subquery will return the maximum version for serial_num, so this will return all rows where serial_num has the maximum value. See this fiddle.
You can use a subquery to find the max values and then join back to your table:
select t1.id,
t1.serial_num,
t1.version
from yourtable t1
inner join
(
select serial_num,
max(version) version
from yourtable
group by serial_num
) t2
on t1.serial_num = t2.serial_num
and t1.version = t2.version
See SQL Fiddle with Demo
Result:
| ID | SERIAL_NUM | VERSION |
-----------------------------
| 1 | 1 | 1 |
| 3 | 2 | 2 |
| 4 | 3 | 1 |
| 5 | 4 | 1 |
| 8 | 5 | 3 |