找到每个键的最新合格行

Find the lastest qualifying row for each key

我的数据库中有这个 table:

我想得到 2 列:id_chantierid_chef
条件:date_fin not null并且有最后一个date_deb.
所以我想得到的行是数字 111.
我该怎么做?

你可以用 rank():

select id_chantier, id_chef
from (select t.*, rank() over (order by date_deb desc) as rnk
      from table t
     ) t
where date_fin is not null and rnk = 1;
SELECT DISTINCT ON (id_chef)
       id_chantier, id_chef
FROM   tbl
WHERE  date_fin IS NOT NULL
ORDER  BY id_chef, date_deb DESC NULLS LAST;

DISTINCT ON

的详细信息
  • Select first row in each GROUP BY group?

根据数据分布,可能有更快的解决方案:

  • Optimize GROUP BY query to retrieve latest record per user

-- 我想获取已关闭的网站 (chantier) 列表(date_fin 不为空)

SELECT *
FROM ztable t
WHERE date_fin IS NOT NULL
AND NOT EXISTS (
    SELECT * FROM ztable nx
    WHERE nx.id_chantier = t.id_chantier -- Same site
    AND nx.date_fin > t.date_fin         -- more recent
    );