Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JOIN on range between current and previous row

Tags:

sql

vertica

could anyone help me please? I have two tables: Prices and Intervals:

   Prices:           Intervals:
   Price         Interval_bound  Category
    16                 5         cheap
    11                 10        cheap
    9                  15        median
    26                 20        median
    6                  25        expensive

I need to join the Category values to the Price according to their interval, where Interval_bound is the lowest bound of category:

Price  Category
 16      median
 11      cheap
 9       cheap
 26      expensive
 6       cheap

I've tried to do it with

select Price, Category from Prices 
left join Intervals on Prices.Price interpolate previous value Interval.Interval_bound

but it gives me only NULL for Category. How can I do it the easiest way? I'm using Vertica.

like image 309
Polly Avatar asked Feb 28 '26 18:02

Polly


1 Answers

You can use lead() to get the next upper bound and then join:

select p.Price, i.Category
from Prices p left join
     (select i.*,
             lead(interval_bound) over (order by interval_bound) as next_interval_bound
      from Intervals i
     ) i
     on p.price >= i.interval_bound and
        (p.price < i.next_interval_bound or i.next_interval_bound is null);
like image 112
Gordon Linoff Avatar answered Mar 02 '26 12:03

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!