I need some help with a query.
We have two columns
Id | AccountId |
---|---|
201 | a-123 |
NULL | a-123 |
NULL | a-123 |
202 | a-234 |
203 | a-345 |
How do I get the Id column to replace the NULL values based on if the AccountId column has the same value with the corresponding NULL value in the ID column?
Like this:
Id | AccountId |
---|---|
201 | a-123 |
201 | a-123 |
201 | a-123 |
202 | a-234 |
203 | a-345 |
I am not sure where to start, I have tried IF()
and coalesce()
but nothing is working.
SELECT Id,
AccountId,
IF(Id IS NULL, coalesce(Id, AccountId), Id)
Gives me this
Id | AccountId |
---|---|
201 | a-123 |
a-123 | a-123 |
a-123 | a-123 |
202 | a-234 |
203 | a-345 |
Any help is much appreciated.
2
Answers
You can write a subquery in a
CASE
statement to achieve this:However, a cleaner solution would be performing a CROSS JOIN and removing the records that are
NULL
during the join:If you need to
UPDATE
your table, wrap the above query in aUPDATE
statement:Result:
db<>fiddle here.
A simple inner join update would do the trick:
https://dbfiddle.uk/hoh4MYHu