【问题标题】:Deduplicating rows ignoring other columns忽略其他列的重复数据删除行
【发布时间】:2021-05-19 01:29:13
【问题描述】:

我需要从多个来源收集一些客户数据并删除重复的 ID,同时维护其他列中的值并保留显示客户来自哪里的列中的 True 值(它可以来自多个资源)。我在为此创建一个 sql 查询时遇到了一些麻烦。我已经尝试过合并功能,但查询持续了将近 1 小时才能完成(约 4000 万行)。

例子:

来源 1:

Name ClientID Source1 Source2 Source3
Name1 123 False True False

来源 2:

Name ClientID Source1 Source2 Source3
Name2 123 True False False

需要的结果:

Name ClientID Source1 Source2 Source3
Name1 or Name 2 123 True True False

我的代码:

WITH ids AS (
  SELECT id FROM source1
  UNION
  SELECT id FROM source2
  UNION
  SELECT id FROM source3
)

SELECT
  COALESCE(s1.name, s2.name, s3.name) AS name,
  id AS clientid,
  CASE WHEN s1.id IS NULL THEN False ELSE True END AS source1,
  CASE WHEN s2.id IS NULL THEN False ELSE True END AS source2,
  CASE WHEN s3.id IS NULL THEN False ELSE True END AS source3
FROM ids i
LEFT JOIN source1 s1 ON i.id = s1.id
LEFT JOIN source2 s2 ON i.id = s2.id
LEFT JOIN source3 s3 ON i.id = s3.id

【问题讨论】:

  • 您的示例数据没有名为 id 的列。
  • 如果您在索引方面需要任何帮助,您必须提供估算计划。
  • @GordonLinoff,这是 ClientID 列,抱歉。

标签: sql oracle


【解决方案1】:

如果id在每个表中都是唯一的,那么full join可能是最简单的方法:

select id,
       (case when s1 is not null then 1 else 0 end) as in_source1,
       (case when s2 is not null then 1 else 0 end) as in_source2,
       (case when s3 is not null then 1 else 0 end) as in_source3
from source1 s1 full join
     source2 s2
     using (id) full join
     source3 s3
     using (id);

我更喜欢01 而不是'true''false'

你也可以union all和聚合:

select id,
       max(in1) as in_source1,
       max(in2) as in_source2,
       max(in3) as in_source3
from ((select id, 1 as in1, 0 as in2, 0 as in3
       from source1 s1
      ) union all
      (select id, 0 as in1, 1 as in2, 0 as in3
       from source1 s1
      ) union all
      (select id, 0 as in1, 0 as in2, 1 as in3
       from source1 s1
      )
     ) s123
group by id;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-18
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2012-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多