There are quite a few times I need to number rows of data based on some grouping column. I often forget how to do it. Well, here’s a couple of examples:
Create table TestTable1 (ID int, InsertDate datetime) Go Insert TestTable1 (ID, InsertDate) Values(1,'8/1/10'), (1,'7/1/10'), (1,'6/1/10'), (2,'3/15/10'), (2,'3/16/10'), (2,'3/13/10'), (2,'3/11/10') --Note the values are out of order for ID 2 Select *, (select count(*) from TestTable1 TT2 where TT1.ID = TT2.ID and TT1.InsertDate < TT2.InsertDate) as 'rank' from TestTable1 TT1 Order by ID, rank
Or a simpler way…
SELECT *, ROW_NUMBER() OVER ( PARTITION BY ID ORDER BY insertdate ) as 'rank' from TestTable1 TT1 Order by ID, rank
Here are some examples and explanations:
- Microsoft Support: How to dynamically number rows in a SELECT Transact-SQL statement
- Data Management and Exchange: Ranking data in Transact SQL


