0

I have a table like this

id dept
1 a
1 b
1 b
2 a
2 b

And I'd like to rename values like this

id dept
1 a
1 b1
1 b2
2 a
2 b1

All values in dept are grouped by id, same departments repeat each group. I'm unsure how to make a loop that does one pass per id (replace 'b' with 'b1'), then a second pass (replace 'b' with 'b2').

Or does once per table, but each statement ends after one replace per id.

Thanks in advance!

4
  • 1
    What is the primary key of your table? To perform such update, we would need a PK. Commented Nov 4, 2022 at 18:28
  • Primary key is 'id' Commented Nov 4, 2022 at 18:30
  • 1
    Yes, but id is not unique, so it can't be a PK. That's the problem here. Commented Nov 4, 2022 at 18:32
  • Clarification: each row needs a unique id? If I were to insert a running sum column as pk, what would the solution look like? Commented Nov 4, 2022 at 18:36

1 Answer 1

1

We don't need to loop. We can just use row_number().

select  id
       ,case when dept = 'b' then dept||row_number() over(partition by id, dept) else dept end as dept
from    t
id dept
1 a
1 b1
1 b2
2 a
2 b1

Fiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.