1

我对已经解决的 Q 有一个后续问题(Oracle SQL:Counting in 4h?)。

如果在显示的数据样本中还有另一列,金额列,我想做与解决方案中建议的一样的事情

select t.*, 
from (select t.*, lag(dt, 6) over (partition by employeeId order by dt) as ord6dt
      from t
     ) t
where dt - ord6dt < 4.0/24

, 一个额外的条件总和金额列 > 10?

所以查询应该只列出那些在 4 小时内有 6 个订单的人 AND sum(order_value)>10

4

1 回答 1

2

您刚刚回顾 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

于 2013-03-13T13:52:27.380 回答