Skip to content
Advertisement

Create Unique ID for Groups of Records

I spent a good amount of time searching for a solution on here and google but came up empty. I thought dense_rank() might work but I can’t get it to do what I’m needing. I’m using SSMS 18. What I’m trying to do is assign a unique ID to groups of records that I have partitioned with row_number().

The data looks like this:

RN Client_ID Date
1 xxxx 2022-08-23
2 xxxx 2022-08-23
3 xxxx 2022-08-23
1 xxxx 2022-08-25
2 xxxx 2022-08-25
1 yyyy 2022-06-10
2 yyyy 2022-06-10
1 gggg 2021-05-06
2 gggg 2021-05-06
3 gggg 2021-05-06
4 gggg 2021-05-06

So each group of records now needs to have a unique ID attributed to them. So it would look something like this:

UnqID RN Client_ID Date
0001 1 xxxx 2022-08-23
0001 2 xxxx 2022-08-23
0001 3 xxxx 2022-08-23
0002 1 xxxx 2022-08-25
0002 2 xxxx 2022-08-25
0003 1 yyyy 2022-06-10
0003 2 yyyy 2022-06-10
0004 1 gggg 2021-05-06
0004 2 gggg 2021-05-06
0004 3 gggg 2021-05-06
0004 4 gggg 2021-05-06

Thanks in advance for any help on this.

Advertisement

Answer

try using a common table entry cte and groupby

output

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