通过最大值连接两个表

问题描述 投票:0回答:2

我有多张桌子。 表 1 包含人员的 IIN(唯一标识号)。表 2 包含 IIN 和 person_id。表3包含table3_id、person_id's、addr_id、date_reg。表4包含addr_id和其他列。我需要停用 table1.iin、table3.date_reg 以及 table4 中针对 table1 中每个 IIN 的所有列。问题是table2和table3之间的关系是一对多的。因此,对于每个 iin,我们都有多个 table3_id。我只需要连接到具有最大 table3_id 的记录。 我怎样才能做到这一点? 我用的是oracle sql

提前致谢

表1:

IIN
0101
0201
0301
0401

表2:

person_id IIN
1 0101
2 0201
3 0301
4 0401

表3:

身份证 person_id id_地址 日期_reg
1 2 12 2022年6月2日
2 2 23 2012年3月6日
3 1 34 2015年5月7日
4 3 45 2020年5月30日
5 3 56 2022年12月6日
6 3 67 2020年10月7日

表4:

id 其他属性
12
23
34
45
56
67

结果:

IIN 日期_reg id_地址 表 4 中的其他属性
0101 2015年5月7日 34
0201 2012年3月6日 23
0301 2020年10月7日 67
0401
    select table1.iin, table4.rka, table4.street, table4.house,                                                         
    table3.date_reg from table1
    left join table2 on table2.iin=table1.iin
    left join table3 on table2.person_id=table3.person_id
    left join table4 on table3.id_addr=table4.id
sql oracle-sqldeveloper
2个回答
0
投票

在主查询中应用子查询即可获得结果。

SQL 示例

SELECT
  t1.IIN,
  t3.date_reg,
  t3.id_addr,
  t4.other_attributes
FROM
  Table1 t1
  JOIN Table2 t2 ON t1.IIN = t2.IIN
  JOIN (
    SELECT
      t3a.person_id,
      MAX(t3a.id) AS max_id
    FROM
      Table3 t3a
    GROUP BY t3a.person_id
  ) subq ON t2.person_id = subq.person_id
  JOIN Table3 t3 ON subq.person_id = t3.person_id AND subq.max_id = t3.id
  JOIN Table4 t4 ON t3.id_addr = t4.id;

0
投票

有很多方法可以实现这一目标。毕竟,这都是关于表 3 并获取其行中每个人的最大日期的。因此,您可以使用现有的查询并添加

and (table3.person_id , table3.date_reg) in
(
  select person_id, max(date_reg)
  from table3
  group by person_id
)

表 3 的

ON
子句。

不过,我更喜欢的是 CTE(又名

WITH
子句)获取顶部表 3 行并使用它们:

with top_table3 as
(
  select *
  from table3
  order by row_number() over (partition by person_id order by date_reg desc)
  fetch first row with ties
)
select t1.iin, t4.rka, t4.street, t4.house, t3.date_reg
from table1 t1
left join table2 t2 on t2.iin = t1.iin
left join top_top_table3 t3 on t3.person_id = t2.person_id
left join table4 t4 on t4.id = t3.id_addr
order by t1.iin;

那么,这个 CTE 是如何工作的?我们对每个人的每一行进行编号,从最新日期的 #1 开始,倒数第二个日期的 #2 开始,依此类推。然后,我们按这些数字对行进行排序,首先与所有需要的编号为 #1 的行建立联系。然后我们说我们想要第一行及其所有关系,即所有最新的行,每人一个。

© www.soinside.com 2019 - 2024. All rights reserved.