【问题标题】:Distinct Match Pair - Teradata/SQL不同的匹配对 - Teradata/SQL
【发布时间】:2015-09-10 00:04:55
【问题描述】:

我正在尝试加入 2 个表以在其中查找匹配对,(请参见图片示例)

加上我的加入条件

table1 
left join (or inner join)
table2 
on table1.metric1 = table2.metric1
and table1.metric2 = table2.metric2
and table1.metric3 = table2.metric3

我得到的结果集是

A 1 , A 2, B 1, B 2 

所需的结果集---因为我想要两个表中的唯一对

A 1 , B 2 as my final result set.

有人可以帮我实现吗? 我尝试了排名,分区,但没有任何效果。 谢谢,

table 1         
ID  Metric1 Metric 2    Metric 3
A   x        y           z
B   x        y           z
C   p        q           r





table 2         
ID  MEtric1     Metric2 Metric3
1   x            y        z
2   x            y        z
3   l            m        n

【问题讨论】:

  • 您的问题不清楚。那么因为A 已经与1 配对,意味着A1 不能与其他任何人配对?
  • 嗨胡安 - 是的,那是正确的。我想要两个表中唯一的 ID 组合。
  • 你试过GROUP BY子句吗?查看您的示例数据,您看到的实际结果对我来说是正确的。
  • 我是论坛的新手,所以我不能发布图片。谢谢,
  • A 1 和 A 2 具有相同的 Metrics,因此除非您使用 GROUP BY 子句,否则它们将匹配,即使那样,您也可能会遇到麻烦

标签: sql teradata


【解决方案1】:

这将为您的示例数据返回正确的结果:

select *
from 
 (
   select t.*,
      row_number()
      over (partition by metric1, metric2, metric3
            order by ID) as rn1
   from table1 as t
 ) as t1
join
 (
   select t.*,
      row_number()
      over (partition by metric1, metric2, metric3
            order by ID) as rn2
   from table2 as t
 ) as t2
 on t1.metric1 = t2.metric1
and t1.metric2 = t2.metric2
and t1.metric3 = t2.metric3
and t1.rn1     = t2.rn2

【讨论】:

  • Dnoeth - 谢谢,我试过这个排名并加入排名。然而;它不适用于包含比我在样本中的记录更多的记录的整个数据集,所以当我在表 2 上进行排名时,它会弄乱排名数字,因为表 2 可能包含更多的 metric1、2、3 组合所以order by 根据数据更改序列,因此 rank 1= rank 2 似乎没有返回所有记录。谢谢
  • @MIT 如果这不起作用,请尝试提供更大的样本。我只是在 postgresql fiddle 中创建了 dnoeth 示例并且工作正常。 Fiddle。也许你可以在那里添加更多数据。
  • 我尝试将更多数据添加到架构中,它返回了正确的结果,也许我可以立即尝试 Dnoeth 的逻辑并更新论坛.. 这很有帮助!谢谢大家。
猜你喜欢
  • 2017-08-09
  • 2021-04-26
  • 2021-03-07
  • 2022-12-02
  • 1970-01-01
  • 1970-01-01
  • 2020-01-14
  • 2022-05-10
  • 1970-01-01
相关资源
最近更新 更多