oracle 按最大值连接两个表

bd1hkmkf  于 12个月前  发布在  Oracle
关注(0)|答案(2)|浏览(111)

我有多个表。表1包含人员的IIN(唯一标识号)。表2包含IIN和person_id。表3包含table3_id,person_id,addr_id,date_reg。表4包含addr_id和其他列。我需要删除table1.iin,table3.date_reg,以及表4为表1中的每个IIN所包含的所有列。问题是表2和表3之间的关系是一对多。因此,对于每个IIN,我们有多个表3_id的。我只需要连接到具有最大table 3_id的记录。我如何才能做到这一点?我使用oracle sql
thanks in advance
表1:
| IIN|
| --|
| 0101 |
| 0201 |
| 0301 |
| 0401 |
表2:
| 个人ID| IIN|
| --|--|
| 1 | 0101 |
| 2 | 0201 |
| 3 | 0301 |
| 4 | 0401 |
表3:
| ID|个人ID| id_address| date_reg|
| --|--|--|--|
| 1 | 2 | 12 |2022年06月02日|
| 2 | 2 | 23 |2012年3月6日|
| 3 | 1 | 34 |2015年05月07日|
| 4 | 3 | 45 |2020年05月30日|
| 5 | 3 | 56 |2022年06月12日|
| 6 | 3 | 67 |2020年10月07日|
表4:
| ID|其他属性|
| --|--|
| 12 ||
| 23 ||
| 34 ||
| 45 ||
| 56 ||
| 67 ||
测试结果:
| IIN| date_reg| id_address|表4中的其他属性|
| --|--|--|--|
| 0101 |2015年05月07日| 34 ||
| 0201 |2012年3月6日| 23 ||
| 0301 |2020年10月07日| 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

字符串

qv7cva1a

qv7cva1a1#

在主查询中应用子查询可以实现您的结果。

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;

字符串

7xzttuei

7xzttuei2#

有很多方法可以实现这一点。毕竟,这是所有关于表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的想要的行的关系。然后我们说我们想要第一行及其所有关系,即所有最新的行,每个人一个。

相关问题