Skip to content
Advertisement

SQL: how to use row_number() function to assign the same number for rows with duplicate ids in a repeating format

I have a table with two columns personid and taskid and want to use the ROW_NUMBER function to add a row that counts up to 3 but will duplicate the number as it counts if there are multiple rows for a personid.

The code below is only ordering by personid and repeating after the number 3, but I need it to order by personid and only go to the next number after all the taskid’s for the personid are assigned to one number, or essentially any duplicate personid’s I want to make sure they all only get one number assigned to it.

Select personid, taskid, 1 + ( (row_number() over (order by personid) – 1) % 3) as numberCount from taskTable

Current Table Being Queried From:

Expected Results After Query:

Advertisement

Answer

Try this below script using DENSE_RANK –

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