Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL Get Max Records By a Column Query

I have a table, I want to get max records by a column. My table:

   id (int) primary key
   topId (int)
   version (int)

Some records have same topId. I want to get max version records which same topId.

Sample records with order:
id:1,2,3,4
topId:1,1,2,2
version:1,2,1,2

I want to get records with query like this:

id:2,4 
topId:1,2    (different topIds)
version:2,2  (Max Versions)
like image 951
egvrcn Avatar asked Nov 19 '25 07:11

egvrcn


1 Answers

You can use ROW_NUMBER with a CTE:

WITH CTE AS
(
   SELECT id, topId , version,
          rn = row_number() over (partition by topId order by version desc)
   FROM dbo.TableName
)
SELECT id, topId , version
FROM CTE
WHERE rn = 1

If you want all records with the max-version replace row_number with dense_rank.

like image 197
Tim Schmelter Avatar answered Nov 20 '25 19:11

Tim Schmelter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!