sql - 在当前行和上一行之间的范围内加入
问题描述
谁能帮帮我?我有两张表:价格和间隔:
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。
解决方案
您可以使用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);
推荐阅读
- java - EDITTEXT Android:需要控制光标位置(阻止或允许)
- swift - 如何将自定义对象数组从 SwiftVC 传递到 ObjCVC?
- javascript - nodejs encoding to base64 string is not working
- python - Python3 诅咒代码在管道中不起作用
- python - Pandas 加入两个 DataFrame,其中一个是数据透视表
- prolog - Prolog - 矩阵 N 乘 N,元素为 [1,...,N^2]
- mysql - SQL删除具有多于一列的重复值的行
- php - 可以在 Wordpress 中跳过 <-- nextpage --> 标记吗?
- python - Modeling swarm behaviour in python
- javascript - Why this ternary operator not working? (more below)