oracle如何合并两行
How do I merge two rows in oracle
我有一个 table,它有多个记录。一条记录有几条数据,另一条有几条数据和更新的数据
ID
Name
gender
birthday
address
salary
1
Jhon
null
null
newyork
null
2
Jhon Deo
Male
1980
null
5000
我在另一个 table 中使用了 id 1 作为外键,所以我需要它。但是id 2有更多的更新数据。
我想将两条记录合并为 id 1 并删除 2
ID
Name
gender
birthday
address
salary
1
Jhon Deo
Male
1980
newyork
5000
如果要优先使用最新的id:
select distinct
last_value(name ignore nulls) over (order by id desc) as name,
last_value(gender ignore nulls) over (order by id desc) as gender,
last_value(birthday ignore nulls) over (order by id desc) as birthday,
last_value(address ignore nulls) over (order by id desc) as address,
last_value(salary ignore nulls) over (order by id desc) as salary
from t;
您应该能够使用这些语句清除多余的记录 (ID 2)。请务必将以下语句中的 your_table
替换为您的实际 table 名称。
UPDATE your_table t1
SET (name,
gender,
birthday,
address,
salary) =
(SELECT nvl(t2.name, t1.name),
nvl(t2.gender, t1.gender),
nvl(t2.birthday, t1.birthday),
nvl(t2.address, t1.address),
nvl(t2.salary, t1.salary)
FROM your_table t2
WHERE t2.id = 2)
WHERE t1.id = 1;
DELETE FROM your_table
WHERE id = 2;
我有一个 table,它有多个记录。一条记录有几条数据,另一条有几条数据和更新的数据
ID | Name | gender | birthday | address | salary |
---|---|---|---|---|---|
1 | Jhon | null | null | newyork | null |
2 | Jhon Deo | Male | 1980 | null | 5000 |
我在另一个 table 中使用了 id 1 作为外键,所以我需要它。但是id 2有更多的更新数据。
我想将两条记录合并为 id 1 并删除 2
ID | Name | gender | birthday | address | salary |
---|---|---|---|---|---|
1 | Jhon Deo | Male | 1980 | newyork | 5000 |
如果要优先使用最新的id:
select distinct
last_value(name ignore nulls) over (order by id desc) as name,
last_value(gender ignore nulls) over (order by id desc) as gender,
last_value(birthday ignore nulls) over (order by id desc) as birthday,
last_value(address ignore nulls) over (order by id desc) as address,
last_value(salary ignore nulls) over (order by id desc) as salary
from t;
您应该能够使用这些语句清除多余的记录 (ID 2)。请务必将以下语句中的 your_table
替换为您的实际 table 名称。
UPDATE your_table t1
SET (name,
gender,
birthday,
address,
salary) =
(SELECT nvl(t2.name, t1.name),
nvl(t2.gender, t1.gender),
nvl(t2.birthday, t1.birthday),
nvl(t2.address, t1.address),
nvl(t2.salary, t1.salary)
FROM your_table t2
WHERE t2.id = 2)
WHERE t1.id = 1;
DELETE FROM your_table
WHERE id = 2;