【问题标题】:How to join tables in sql to exclude rows already matched from further consideration如何在 sql 中连接表以排除已匹配的行,以防进一步考虑
【发布时间】:2021-11-13 18:06:57
【问题描述】:

我有 2 个表格,如下所示。我正在尝试在 order_code 上将表 1 连接到表 2,这样一旦行匹配,任一表中的相应 id 都不应再次显示在连接表上。匹配应按两个表中日期的升序进行。还显示了预期结果:

表 1:

PK1 order_code Date1
1 XYZ 1/1/2021
2 ABC 1/2/2021
3 ABC 1/3/2021
4 XYZ 1/4/2021

表 2:

PK2 order_code Date2
1 ABC 2/7/2021
2 XYZ 2/6/2021
3 ABC 2/5/2021
4 XYZ 2/8/2021
5 ABC 2/11/2021
6 XYZ 2/14/2021

预期结果:

PK1 order_code Date1 PK2 order_code Date2
1 XYZ 1/1/2021 2 XYZ 2/6/2021
2 ABC 1/2/2021 3 ABC 2/5/2021
3 ABC 1/3/2021 1 ABC 2/7/2021
4 XYZ 1/4/2021 4 XYZ 2/8/2021

如果需要更清晰的说明,请告诉我,我可以尝试更好地解释这一点。感谢所有帮助!

【问题讨论】:

  • 当你“从任一表中写入相应的 id 不应该出现”时,你的意思是什么?

标签: sql sql-server


【解决方案1】:

通过 order_code 和 order_code 中的行位置加入。

select t1.PK PK1, t1.order_code, t1.Date Date1, t2.PK PK2, t2.order_code, t2.Date Date2
from (
   select *, row_number() over(partition by order_code order by Date) rn
   from table1
) t1
join (
   select *, row_number() over(partition by order_code order by Date) rn
   from table2
) t2 on t1.order_code = t2.order_code and t1.rn = t2.rn);

【讨论】:

  • 谢谢!正是我想要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多