In SQL Server, you can use the ROW_NUMBER() function to assign a unique label to each row within a specific group of rows. The ROW_NUMBER() function assigns a unique number to each row within a result set, based on the order specified in the ORDER BY clause.

Here is an example of how you might assign labels to each ID in SQL Server:

Copy codeWITH cte AS (
  SELECT id, ROW_NUMBER() OVER (PARTITION BY id ORDER BY id) AS label
  FROM your_table
)
SELECT id, label
FROM cte

In the above query, a common table expression (CTE) is used to assign a label to each ID using the ROW_NUMBER() function. The function assigns a unique label to each ID, based on the order of the ID in the table. The query then selects the ID and label columns from the CTE.

You can also use DENSE_RANK() function instead of ROW_NUMBER() function to assign labels to each ID and this function would not leave any gap between the labels.

Copy codeWITH cte AS (
  SELECT id, DENSE_RANK() OVER (ORDER BY id) AS label
  FROM your_table
)
SELECT id, label
FROM cte

It will give you the unique label for each unique ID.

(Visited 26 times, 1 visits today)
Was this article helpful?
YesNo
Close Search Window