使用递归查询,它取最后一个
calls
作为
lag1
移动所有其他
lag
回顾过去:
with
s as (
select rn, call_dt, calls,
lag(calls, 4) OVER (partition by dow order by call_dt) as lag4,
lag(calls, 3) OVER (partition by dow order by call_dt) as lag3,
lag(calls, 2) OVER (partition by dow order by call_dt) as lag2,
lag(calls, 1) OVER (partition by dow order by call_dt) as lag1
from (
select 0 rn, tbl_1.* from tbl_1 union all
select row_number() over (order by call_dt), tbl_2.* from tbl_2)),
c(rn, call_dt, calls, lag1, lag2, lag3, lag4) as (
select rn, call_dt, (1 * lag1) + (0.8 * lag2) + (0.5 * lag3) + (0.3 * lag4),
lag1, lag2, lag3, lag4
from s where rn = 1
union all
select s.rn, s.call_dt, (1 * c.calls) + (0.8 * c.lag1) + (0.5 * c.lag2) + (0.3 * c.lag3),
c.calls, c.lag1, c.lag2, c.lag3
from s join c on c.rn+1 = s.rn)
select * from c
s
-基本上是您的查询,我添加了行编号。
c
CTE在哪里
rn = 1
是我们的锚,第一步。然后我们逐行添加下一步,
向右
结果:
RN CALL_DT CALLS LAG1 LAG2 LAG3 LAG4
------ ----------- ---------- ---------- ---------- ---------- ----------
1 2018-10-15 21,5 1 8 15 22
2 2018-10-22 30,8 21,5 1 8 15