Это выглядит как left join
:
select a.*, coalesce(b.item_pos, 0) as item_pos
from a left join
(select distinct on (b.item_id, b.item_clust) b.*
from b
order by b.item_id, b.item_clust, b.date desc
) b
using (item_id, item_clust);
или боковое соединение:
select a.*, coalesce(b.item_pos, 0) as item_pos
from a left join lateral
(select b.*
from b
where b.item_id = a.item_id and
b.item_clust = a.item_clust
order by b.date desc
limit 1
) b
on true; -- always do the left join even when there are no matches
РЕДАКТИРОВАТЬ:
Если вы хотите самую последнюю позицию " на дату A
, затем используйте боковое соединение:
select a.*, coalesce(b.item_pos, 0) as item_pos
from a left join lateral
(select b.*
from b
where b.item_id = a.item_id and
b.item_clust = a.item_clust and
b.date <= a.date
order by b.date desc
limit 1
) b
on true; -- always do the left join even when there are no matches