Increment Row Number on Group

后端 未结 2 1131
旧巷少年郎
旧巷少年郎 2020-12-23 16:07

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

相关标签:
2条回答
  • 2020-12-23 16:47

    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
    
    0 讨论(0)
  • 2020-12-23 16:59

    That can be accomplished with the DENSE_RANK() function:

      DENSE_RANK() OVER(Order By [shade]) as t_index
    
    0 讨论(0)
提交回复
热议问题