我需要按复杂条件对表中的行进行分组。假设我有一个表:
create table items (
name text,
price float
)
它有这样的项目:
foo | 42.0
foo | 42.5
foo | 100
bar | 42
前两个foo
的价格相差不到10%(条件类似于a.price / b.price between 0.9 and 1.1
(,所以它们应该进入单个组,而其他(3rd(foo
和bar
应该在不同的组中,预期结果应该是这样的:
item | min_price | max_price | count
foo | 42 | 42.5 | 2
foo | 100 | 100 | 1
bar | 42 | 42 | 1
是否可以使用 SQL 查询?
根据您评论中的假设,您可以查找滞后以根据相对价格定义组的开始位置。 然后做一个"组开始"的累积总和来计算分组 id,并聚合:
select item, min(price), max(price), count(*)
from (select i.*,
count(*) over (filter where prev_price < 0.9 * price) over (partition by item order by price) as grp
from (select i.*,
lag(price) over (partition by item order by price) as prev_price
from items i
) i
) i
group by item
order by item, min(price);