我有这个小 table 具有重复的 ID 和名称,我想使用那里的 ID 将空值替换为名称

I have this small table having duplicate id and names and I want to replace null values with names using there ID

我通过自连接得到它:

select a.id, a.name, b.id, b.name, nvl(a.name,b.name)
from names a
join names b
on a.id = b.id
where a.name is null and b.name is not null;

但不知道我如何在 table 中更新它。 我试过更新语句但没有用

[]

问题是在没有空 name 列的行中没有唯一的 [id, name] 组合。

SQL> select * From test;

        ID NAME
---------- ------
         1 naya
         1 naya
         2 amar
         3 dhruv           --> here
         4 shyla
         4 shyla
         3 diya            --> here
         5 ananya
         6 ishaan
         5
         2
         2
         1
         3

14 rows selected.

SQL>

那么,对于 ID = 3,您想获得哪个名字?你不能同时拥有两者,所以 - 一种选择是 select any,例如最大值

SQL> update test a set
  2    a.name = (select max(b.name)
  3              from test b
  4              where b.id = a.id
  5             )
  6  where a.name is null;

5 rows updated.

结果:

SQL> select * From test;

        ID NAME
---------- ------
         1 naya
         1 naya
         2 amar
         3 dhruv
         4 shyla
         4 shyla
         3 diya
         5 ananya
         6 ishaan
         5 ananya
         2 amar
         2 amar
         1 naya
         3 diya

14 rows selected.

SQL>

从 Oracle 12 开始,您可以使用:

UPDATE names n
SET    name = (SELECT name
               FROM   names x
               WHERE  x.id = n.id
               ORDER BY name NULLS LAST
               FETCH FIRST ROW ONLY)
WHERE  name IS NULL

db<>fiddle here