【问题标题】:How do I merge two rows in oracleoracle如何合并两行
【发布时间】:2021-05-16 15:41:30
【问题描述】:

我有一个包含多条记录的表。一条记录有一些数据,另一条有一些数据并更新了

ID Name gender birthday address salary
1 Jhon null null newyork null
2 Jhon Deo Male 1980 null 5000

我在另一个表中使用了 id 1 作为外键,所以我需要它。但是 id 2 有更多更新的数据。

我想将两条记录合并为 id 1 并删除 2

ID Name gender birthday address salary
1 Jhon Deo Male 1980 newyork 5000

【问题讨论】:

  • 如果要优先考虑id = 2,为什么还要id = 1
  • 如果一列中有多个行有非NULL 值,如name,规则是什么? ids 的规则是什么?
  • 如果多行非空我更喜欢更新的一个(id = 2)并且id是主键
  • 整件事的意义为零。如果输入也有 ID = 3,名称 = 'Jhon Bug' 并且其他列中有不同的数据怎么办?你怎么知道 ID = 1 必须与 ID = 2 配对(和更新),而不是 ID = 3?我不知道您如何合理地解决此类问题。
  • @mathgut 我知道我的数据。项目从手动数据开始,但我们建立了一个集成,一些重复的数据出现在我的桌子上。我想使用旧记录,我想获得新的数据。所以我需要合并新旧。这不是零意义。这是案例

标签: sql oracle merge sql-update


【解决方案1】:

您应该能够使用这些语句清除额外记录 (ID 2)。请务必将以下语句中的 your_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;

【讨论】:

    【解决方案2】:

    如果要优先考虑最新的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=1 并删除 id=2
    猜你喜欢
    • 1970-01-01
    • 2022-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-22
    相关资源
    最近更新 更多