Increment Row Number on Group

I am working on a query for SQL Server 2005 that needs to return data with two 'index' fields. The first index 't_index' should increment every time the 'shade' column changes, whilst the second index increments within the partition of the values in the 'shade' column:

t_index s_index shade
1       1       A
1       2       A
1       3       A
1       4       A
1       5       A
2       1       B
2       2       B
2       3       B
2       4       B
2       5       B

To get the s_index column I am using the following:

Select ROW_NUMBER() OVER(PARTITION BY [shade] ORDER BY [shade]) as s_index

My question is how to get the first index to only increment when the value in the 'shade' column changes?


Solution 1:

That can be accomplished with the DENSE_RANK() function:

  DENSE_RANK() OVER(Order By [shade]) as t_index

Solution 2:

You can try to use DENSE_RANK() for that:

SELECT
    shade,
    s_index = ROW_NUMBER() OVER(PARTITION BY [shade] ORDER BY [shade]),
    t_index = DENSE_RANK() OVER (ORDER BY [shade])
FROM dbo.YourTableNameHEre

Gives output:

shade  s_index  t_index
  A      1        1
  A      2        1
  A      3        1
  A      4        1
  A      5        1
  B      1        2
  B      2        2
  B      3        2
  B      4        2
  B      5        2