繁体   English   中英

SQL join 2 rows into 1 with conditions

[英]SQL join 2 rows into 1 with conditions

我有一个包含更新和插入值的表。 因此,大多数 ID 有 2 行,一个用于插入,另一个用于更新(有一个“运算符”列,其值为 UPDATED 或值 INSERTED)。 样本数据:

operator | ID | row2 | row3
===========================
updated  | 01 |      | 231
===========================
inserted | 01 | abc  | 123
===========================
updated  | 02 | khj  | 567
===========================
inserted | 02 | klo  | 567
===========================
inserted | 03 | nmb  | 900

我的任务是将这 2 行合并为 1,按它们的 ID 对它们进行分组。 但是,所有值都必须来自“更新”行,并且如果“更新”中有一些 NULL 值,它们必须来自“插入”行。

期望的结果:

 ID  | row2 | row3
==================
 01  | abc  | 231
==================
 02  | khj  | 567
==================
 03  | nmb  | 900
==================

目标是让所有不同的 ID 具有最新的数据。

有谁知道如何做到这一点?

我尝试实现以下逻辑,但它没有返回最新数据:

SELECT
    ID,
    MAX(Field1) AS Field1,
    MAX(Field2) AS Field2
FROM
    table_name
GROUP BY
    ID;

你可以试试这个——

Select 
u.ID, 
NVL(u.row2, i.row2), 
NVL(u.row3, i.row3) -- and so on for more columns
from
(Select * from tableName where operator = 'updated') u,
(Select * from tableName where operator = 'inserted') i
where u.ID = i.ID;

如果您的表中的数据没有任何带有“更新”的记录,则您需要 LEFT OUTER JOIN,因此您可以使用以下查询 -

Select 
i.ID, 
NVL(u.row2, i.row2), 
NVL(u.row3, i.row3) -- and so on for more columns
from
(Select * from tableName where operator = 'updated') u,
(Select * from tableName where operator = 'inserted') i
where u.ID(+) = i.ID;

如果我理解正确,你想要 select 行,先update ,如果没有更新,再insert 所以一种方法是:

select t.*
from table_name  t
where t.operator = 'UPDATED' or
      not exists (select 1
                  from table_name t2
                  where t2.id = t.id and t2.operator = 'UPDATED'
                 );

你可以这样做:

   SELECT
      a.*
    FROM
      table_name a
    WHERE a.operator = 'UPDATED'
    UNION ALL
    SELECT
      b.*
    FROM
      table_name b
    WHERE b.operator = 'INSERTED'
      AND b.ID NOT IN
      (SELECT
        c.ID
      FROM
        table_name c
      WHERE c.operator = 'UPDATED'
        AND c.ID = b.ID)

注意:如果您想要或需要删除重复项,可以将:UNION ALL 替换为 UNION,

大方地。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM