If you can use window functions (and not have access to first_value
function):
with cte as ( select row_number() over(partition by a.active_id order by b.date asc) as rn1, row_number() over(partition by a.active_id order by b.date desc) as rn2, a.active_id, b.date, b.city from tbl_a as a inner join tbl_b as b on b.id = a.id ) select c.active_id, c1.date, c2.city from (select distinct active_id from cte) as c left outer join cte as c1 on c1.active_id = c.active_id and c1.rn1 = 1 left outer join cte as c2 on c2.active_id = c.active_id and c2.rn2 = 1
demo sql
If you can use the first_value
function:
with cte as ( select first_value(b.date) over(partition by a.active_id order by b.date asc) as date, first_value(b.city) over(partition by a.active_id order by b.date desc) as city, a.active_id from tbl_a as a inner join tbl_b as b on b.id = a.id ) select distinct active_id, date, city from cte
source share