SQL:快速累积频率查询(postgres)

时间:2011-01-12 19:56:44

标签: sql postgresql cumulative-frequency

我希望从我们的数据库中获取累积频率数据。我创建了一个简单的临时表,其中包含我们看到的所有唯一状态更新计数,以及具有该状态更新量的用户数。

     Table "pg_temp_4.statuses_count_tmp"
     Column     |  Type   | Modifiers 
----------------+---------+-----------
 statuses_count | integer | 
 frequency      | bigint  | 
Indexes:
    "statuses_count_idx" UNIQUE, btree (statuses_count)

我目前的查询是:

select statuses_count, frequency/(select * from total_statuses)::float, (select sum(frequency)/(select * from total_statuses)::float AS percentage from statuses_count_tmp WHERE statuses_count <= SCT.statuses_count) AS cumulative_percent  FROM statuses_count_tmp AS SCT ORDER BY statuses_count DESC;

但是这需要相当长的一段时间,查询的数量会很快增长。因此,对于我所拥有的约50,000行,我正在查看要读取的50k因子行。坐在这里看着查询磨掉了我希望有一个更好的解决方案,我还没有通过。

希望得到这样的东西:

0       0.26975161      0.26975161
1       0.15306534      0.42281695
2       0.05513516      0.47795211
3       0.03050646      0.50845857
4       0.02064444      0.52910301

1 个答案:

答案 0 :(得分:2)

假设你有PostgreSQL 8.4或更高版本,应该可以解决窗口函数问题。我猜total_statuses是一个select sum(frequency) from statuses_count_tmp行的视图或临时表?我在这里写了一个CTE,它应该在语句的持续时间内只计算一次结果:

with total_statuses as (select sum(frequency) from statuses_count_tmp)
select statuses_count,
       frequency / (select * from total_statuses) as frequency,
       sum(frequency) over(order by statuses_count)
           / (select * from total_statuses) as cumulative_frequency
from statuses_count_tmp

如果没有8.4的窗口函数,最好的办法就是迭代处理数据:

create type cumulative_sum_type as ( statuses_count int, frequency numeric, cumulative_frequency numeric );
create or replace function cumulative_sum() returns setof cumulative_sum_type strict stable language plpgsql as $$
declare
  running_total bigint := 0;
  total bigint;
  data_in record;
  data_out cumulative_sum_type;
begin
  select sum(frequency) into total from statuses_count_tmp;
  for data_in in select statuses_count, frequency from statuses_count_tmp order by statuses_count
  loop
    data_out.statuses_count := data_in.statuses_count;
    running_total := running_total + data_in.frequency;
    data_out.frequency = data_in.frequency::numeric / total;
    data_out.cumulative_frequency = running_total::numeric / total;
    return next data_out;
  end loop;
end;
$$;
select * from cumulative_sum();