我有下表:
date | ratio | revenue
---------|-------|-----------
03-30-18 | 1.2 | 918264
03-31-18 | 0.94 | 981247
04-01-18 | 1.1 | 957353
04-02-18 | 0.99 | 926274
04-03-18 | 1.05 |
04-04-18 | 0.97 |
04-05-18 | 1.23 |
如您所见,2018 年 4 月 3 日及以后尚未发生,因此这些天没有收入输入。但我对未来的日子有一个比例。我想使用我确实过去 4 天的平均收入,并将其乘以比率来做出未来的收入预测。
结果,我希望得到下表:
date | ratio | revenue
---------|-------|-----------
03-30-18 | 1.2 | 918264
03-31-18 | 0.94 | 981247
04-01-18 | 1.1 | 957353
04-02-18 | 0.99 | 926274
04-03-18 | 1.05 | 993073.73
04-04-18 | 0.97 | 917410.97
04-05-18 | 1.23 | 1163314.94
我认为不需要窗口函数,所以我将其表述为:
select t.date, t.ratio,
coalesce(t.revenue, a.avg4 * ratio) as revenue
from t cross join
(select avg(revenue) as avg4
from (select t.*
from t
where t.revenue is not null
order by date desc
limit 4
) t
) a
order by date;
您应该在初始查询中计算平均值,并使用
revenue
中包含空值的行的值:
with the_avg as (
select avg
from (
select
date,
revenue,
avg(revenue) over (order by date rows between 4 preceding and current row)
from my_table
) s
where revenue is null
order by date
limit 1
)
select
date,
ratio,
case when revenue is not null then revenue
else round(avg * ratio, 2) end as revenue
from my_table
cross join the_avg
order by date;