我必须使用参数“users”的运行总值。这是脚本(简化):
with us_data as (
select
count(us.*) as us_reg,
count(us.*) filter (where status = 'active') as us_active,
date_trunc('day', us.created_at) as rp_date
from public.account_users us
group by rp_date)
select
sum(us_reg) over (rows between unbounded preceding and current row)::int as total_users,
rp_date
from us_data
order by rp_date;
由于表每天都会增长,因此脚本运行缓慢,因为它必须从一开始就计算所有用户。 我可以将前一天(或任何其他前一天)的数据存储在不同的表中,并更改脚本以获取从那天到现在的 Total_users 。然后我可以添加保存的结果并再次将数据存储在结果表中。
该任务是否有更优化的解决方案来加快用户帐户运行总计的计算速度?
更简单、更快的等价物:
SELECT sum(count(*)::int) OVER () AS total_users
, date_trunc('day', us.created_at) AS rp_date
FROM public.account_users us
GROUP BY rp_date
ORDER BY rp_date; -- !
您可以在同一个
SELECT
中对聚合函数运行窗口函数。
CTE 中的us_active
只是我剪掉的死货。
并且
rows between unbounded preceding and current row
是默认值,因此您不必拼写出来。
您确实在窗口函数中省略了
ORDER BY
,该函数通常可以工作,因为它默认为外部ORDER BY
,但这(与上面的默认值不同)只是一个实现细节,并不能保证。可以肯定的是:
SELECT sum(count(*)::int) OVER (ORDER BY date_trunc('day', us.created_at)) AS total_users
, date_trunc('day', us.created_at) AS rp_date
FROM public.account_users us
GROUP BY rp_date
ORDER BY rp_date; -- !
将运行总和存储在某种物化视图中,并且仅添加“昨天”的最后一个增量,显然对于长系列来说会使其速度更快。它增加了相当多的开销,所以这个系列必须持续一段时间才能支付额外的成本。
相关: