有没有办法根据某些值将行分成组?

Is there a way to split rows into groups based on certain values?

考虑这个 table:

我想根据它们的 ID 和价格将这些行分组:只要两行具有相同的 ID 和价格 并且不被任何其他行分割他们属于同一组,所以我希望输出是这样的:

我尝试使用 window 函数,但最后一行与前 3 行具有相同的组。我是否遗漏了什么?

这是一个 gaps-and-islands 问题。一种方法是使用lag()检测变化,然后求和:

select t.*,
       sum(case when prev_price = price then 0 else 1 end) over
           (partition by id order by dt) as group_num
from (select t.*,
             lag(price) over (partition by id order by dt) as prev_price
      from t
     ) t