I have the below table:
Name |
---|
(null) |
Name1 |
Name2 |
Name3 |
(null) |
Name4 |
I would like to generate this output:
Name | Output |
---|---|
(null) | Anon1 |
Name1 | Name1 |
Name2 | Name2 |
Name3 | Name3 |
(null) | Anon2 |
Name4 | Name4 |
With the below query, I’m able to generate the below table
WITH aux ( name ) AS ( SELECT NULL FROM dual UNION ALL SELECT 'Name1' FROM dual UNION ALL SELECT 'Name2' FROM dual UNION ALL SELECT 'Name3' FROM dual UNION ALL SELECT NULL FROM dual UNION ALL SELECT 'Name4' FROM dual ) SELECT a.*, nvl(name, concat('Anon', ROW_NUMBER() OVER( PARTITION BY name ORDER BY ROWNUM ))) output FROM aux a;
Name | Output |
---|---|
Name1 | Name1 |
Name2 | Name2 |
Name3 | Name3 |
Name4 | Name4 |
(null) | Anon1 |
(null) | Anon2 |
However, the nulls appear at the end instead of the original order. Is there a way to prevent this?
Advertisement
Answer
SQL tables represent unordered (multi)sets. There is no ordering, unless a column specifies that ordering. Without a column that specifies the ordering of the rows, your question does not make sense.
If I assume that you have an ordering column, then you can do:
select name, coalesce(name, 'anon' || row_number() over (partition by name order by <ordering col> ) as output from aux order by <ordering col>;