首页 > 解决方案 > 在两个表中查询 Postgres

问题描述

我需要带来咨询结果。

我需要带上每个 inst_code 的最新版本,以及它的名字(表 B)

我目前的情况

标签: sqlpostgresqlgreatest-n-per-group

解决方案


在 Postgres 中,您可以使用它distinct on来解决这个 top-1-per-group 问题:

select distinct on(a.inst_code)
    a.inst_code,
    b.inst_name,
    a.version,
    a.status,
    a.date
from tablea a
inner join table b on b.inst_code = a.inst_code
order by a.inst_code, a.version desc, a.date desc

推荐阅读