Skip to content
Advertisement

How to give row number for consecutive combination and duplicate it for duplicates

I created simple table to illustrate my problem:

DECLARE @Test TABLE
          (
              id int,
              Type VARCHAR(10),
              SectionId int
          )

Insert into @Test
SELECT 1,'RED', 100
UNION ALL SELECT 2, 'RED', 100
UNION ALL  SELECT 3, 'BLUE', 100
UNION ALL SELECT  4, 'RED', 200
UNION ALL SELECT  5, 'BLUE', 200
UNION ALL SELECT  6, 'RED', 300
UNION ALL SELECT  7, 'BLUE', 300
UNION ALL SELECT  8, 'BLUE', 300

So I want to give row number to each row but repeat it when Type and SectionId is the same:

id, Type, SectionId, RowNumber
1, 'RED', 100        1
2, 'RED', 100        1
3, 'BLUE',100        2
4, 'RED', 200        1
5, 'BLUE',200        2
6, 'RED', 300        1
7, 'BLUE',300        2
8, 'BLUE',300        2

if I try ROW_NUMBER() Over (Partition by SectionId, Type Order by id) I will get result like that:

id, Type, SectionId, RowNumber
1, 'RED', 100        1
2, 'RED', 100        2
3, 'BLUE',100        1
4, 'RED', 200        1
5, 'BLUE',200        1
6, 'RED', 300        1
7, 'BLUE',300        1
8, 'BLUE',300        2

Please tell me if there are any way to do that.

Database that I used is Microsoft SQL Server (ver. 14.00.3045)

Advertisement

Answer

Use dense_rank() instead of row_number():

SELECT id, type, sectionid
     , dense_rank() OVER (PARTITION BY sectionid ORDER BY type DESC) AS RowNumber
FROM test
ORDER BY id;
id          Type        SectionId   RowNumber 
----------  ----------  ----------  ----------
1           RED         100         1         
2           RED         100         1         
3           BLUE        100         2         
4           RED         200         1         
5           BLUE        200         2         
6           RED         300         1         
7           BLUE        300         2         
8           BLUE        300         2        

db<>fiddle

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement