declare @n table (id int);
insert into @n values (1), (2), (3), (5), (6), (7), (8), (15), (16), (20), (21), (22), (23), (30), (31), (55)
select diff, min(id) as range_from, max(id) as range_to
from (
select
id
, id - row_number() over (order by id) as diff
from @n
) x
group by diff
having min(id) <> max(id) -- опционально, если нужны именно диапазоны
order by diff
SELECT distinct account_id,
LAST_VALUE(amount)over(PARTITION BY account_id ORDER BY payment_date RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) last_payment
FROM kollecto.payments
where account_id in (759318,759320,759322,759324)
order by account_id;