Sql 按模糊条件分组

Sql 按模糊条件分组,sql,postgresql,Sql,Postgresql,我需要根据一个复杂的条件对表格中的行进行分组。假设我有一张桌子: create table items ( name text, price float ) 它有如下项目: foo | 42.0 foo | 42.5 foo | 100 bar | 42 item | min_price | max_price | count foo | 42 | 42.5 | 2 foo | 100 | 100 | 1 bar | 42 | 42 | 1 前两个foo的价格相差不到10%。条

我需要根据一个复杂的条件对表格中的行进行分组。假设我有一张桌子:

create table items (
   name text,
   price float
)
它有如下项目:

foo | 42.0
foo | 42.5
foo | 100
bar | 42
item | min_price | max_price | count
foo | 42 | 42.5 | 2
foo | 100 | 100 | 1
bar | 42 | 42 | 1
前两个foo的价格相差不到10%。条件类似于a.price/b.price介于0.9和1.1之间,因此它们应属于单个组,而其他第三个foo和bar应属于单独的组,预期结果如下:

foo | 42.0
foo | 42.5
foo | 100
bar | 42
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);

1标记您正在使用的数据库。2如果您有42,42.5,43,43.5,44,44.5,46,46.5,47的行怎么办。第一个值和最后一个值相差超过10%,但中间值均在该范围内。1。我会接受任何数据库的答案,但最好是postgres。2.让我们假设没有这样的项目,或者它们都应该属于一个组。您可以为每个组确定适当的规范值,例如,四舍五入到10的最近倍数吗?或者您需要动态查找组吗?这不行,因为89和90将转到不同的组