You're not getting the desired results because GRADE
is part of the grouping. Take a look at the data:
SERIAL SKU GRADE ID
HA501 R2022 2 2011063
HA501 R2022 1 2011052
HA502 R2033 2 2011051
HA502 R2033 3 2011048
HA503 R2044 1 2011034
HA503 R2044 2 2011023
You're expecting to get back the following row for SERIAL = HA501
:
HA501 R2022 2 2011063
However, there are multiple GRADE
values for that SERIAL/SKU. Therefore, you'll need to remove the GRADE
from the GROUP BY
, otherwise you'll get the MAX(ID)
for each combination of SERIAL, SKU, GRADE (which, in this case, would result in basically every row being returned).
So, the correct query will look like this:
SELECT SERIAL, SKU, MAX(id) as MaxID
FROM TABLEA
GROUP BY SERIAL, SKU
However, that won't include the GRADE
column. If you need the corresponding GRADE
returned as well, you'll need to do this (as Cybernate has already shown):
SELECT SERIAL, SKU, GRADE, ID
FROM TABLEA
WHERE ID IN (SELECT MAX(ID) FROM TABLEA GROUP BY SERIAL, SKU)
Which gets a list of the maximum IDs we established in the previous query and returns all data matching those IDs.
Alternatively, try this:
SELECT a.SERIAL, a.SKU, a.GRADE, a.ID
FROM TABLEA a
INNER JOIN (
SELECT SERIAL, SKU, MAX(ID) as ID FROM TABLEA GROUP BY SERIAL, SKU) b
ON A.SERIAL = B.SERIAL AND A.SKU = B.SKU AND A.ID = B.ID