您刚刚回顾 6 行的解决方案(这可能不是满足 4 小时前的第一个订单)。因此,添加另一个分析以保持该解决方案:
select *
from (select t1.*, lag(dt, 6) over (partition by employee order by dt) as ord6dt,
sum(order_value) over (partition by employee order by dt rows 6 preceding) val
from emptest t1
)
where dt - ord6dt < 4.0/24
and val >= 10;
将再次只计算 6 行(如果我们在过去四个小时内有超过 6 个订单,这可能会错过一些真正的匹配)。
我们可以对此进行建模:
select *
from (select *
from emptest
model
dimension by (employee, dt)
measures ( order_value, order_id, 0 order_sum, 0 number_of_orders)
rules (
order_sum[any,any] = sum(order_value)[cv(employee), dt between cv(dt)-(4/24) and cv(dt)],
number_of_orders[any,any] = count(*)[cv(employee), dt between cv(dt)-(4/24) and cv(dt)]
))
where order_sum > 10
and number_of_orders >= 6
order by employee, dt;
它会在 4 或更多时查找 number_of_orders,并且还会检查 4 小时内的计数。
小提琴:http ://sqlfiddle.com/#!4/3045d/1