В вашем случае подойдет простое агрегирование - при условии, что 0
является самым ранним значением:
select id, max(number_of_int_customers)
from t
where effective_date in ('2019-10-01', '2020-02-01')
group by id
having min(number_of_int_customers) = 0;
Очевидно, что это неверно, если значения могут уменьшиться до нуля. Но это предложение having
решает эту проблему:
having min(case when number_of_int_customers = 0 then effective_date end) = min(effective_date)
Альтернативой является использование оконных функций, таких как first_value()
:
select distinct id, last_noic
from (select t.*,
first_value(number_of_int_customers) over (partition by id order by effective_date) as first_noic,
first_value(number_of_int_customers) over (partition by id order by effective_date desc) as last_noic,
from t
where effective_date in ('2019-10-01', '2020-02-01')
) t
where first_noic = 0;
Хммм, если подумать, мне нравится lag()
лучше:
select id, number_of_int_customers
from (select t.*,
lag(number_of_int_customers) over (partition by id order by effective_date) as prev_noic
from t
where effective_date in ('2019-10-01', '2020-02-01')
) t
where prev_noic = 0;