Increment Row Number on Group

SqlSql ServerSql Server-2005

Sql Problem Overview


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?

Sql Solutions


Solution 1 - Sql

That can be accomplished with the DENSE_RANK() function:

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

Solution 2 - Sql

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCaledonian CoderView Question on Stackoverflow
Solution 1 - SqlMe.NameView Answer on Stackoverflow
Solution 2 - Sqlmarc_sView Answer on Stackoverflow