我的数据库中有这个表:
我希望获得2列:id_chantier
和id_chef
条件:date_fin not null
并且具有最后date_deb
因此,我想要获取的行数为1
和11
我怎么能这样做?
答案 0 :(得分: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
根据数据分布,可能会有更快的解决方案:
答案 1 :(得分:0)
您可以使用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;
答案 2 :(得分:0)
- 我想得到关闭的网站列表(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
);