当前行和前一行之间的范围内连接(JOIN)

3

请问有人能帮我一下吗?我有两个表:Prices和Intervals:

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

我需要按照它们的区间将类别值与价格匹配,其中 Interval_bound 是类别的最低边界:

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

我已经尝试使用以下方法进行操作:

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

但是它只给我 NULL 值作为类别。最简单的方法是什么?我正在使用 Vertica 数据库。

2个回答

3
你可以使用 lead() 来获取下一个上限,然后使用 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);

1

我很困惑 - 为什么你的版本不起作用?

-- your input ..
WITH
prices(price) AS (
          SELECT 16
UNION ALL SELECT 11
UNION ALL SELECT  9
UNION ALL SELECT 26
UNION ALL SELECT  6
)
, 
-- your other input 
intervals(interval_bound,category) AS (
          SELECT  5,'cheap'
UNION ALL SELECT 10,'cheap'
UNION ALL SELECT 15,'median'
UNION ALL SELECT 20,'median'
UNION ALL SELECT 25,'expensive'
)
-- the way I would write it ...
SELECT
  p.price
, i.category
FROM prices p
LEFT JOIN intervals i
ON p.price INTERPOLATE PREVIOUS VALUE i.interval_bound
;
 price | category
-------+-----------
     6 | cheap
     9 | cheap
    11 | cheap
    16 | median
    26 | expensive

-- the way you wrote it ...
select Price, Category from Prices
left join Intervals on Prices.Price interpolate previous value Intervals.Interval_bound;
 Price | Category
-------+-----------
     6 | cheap
     9 | cheap
    11 | cheap
    16 | median
    26 | expensive

在你的情况下出了什么问题?

你知道吗,我刚刚检查了一下,问题出在我的愚蠢的非空过滤器上,这导致了正确结果被清除,所以实际上我的版本也是正确的!谢谢你指出来 :) - Polly

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接