I have a table that looks like this:-
TABLEA
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
I wish to extract the above SERIAL, SKU & GRADE based on the latest ID, like this:
FINAL OUTPUT
SERIAL SKU GRADE ID
HA501 R2022 2 2011063
HA502 R2033 2 2011051
HA503 R2044 1 2011034
I was trying to using SQL:
select
SERIAL, SKU, GRADE, MAX(ID)
from tableA
group by SERIAL, SKU, GRADE
but somehow the output doesn’t seems right.
Can someone help me ?
Thanks.
Should you be using SQL Server 2005 and newer, you could use a CTE with the
ROW_NUMBERconstruct:This will “partition” your data by
Serial,SKU,Gradeand for each group of the same values, it will sequentially number the rows starting at 1, ordered by descending ID (so the largest/newest ID will be RowNum = 1).