Sql 在postgres中跨多个窗口对行值进行分组

Sql 在postgres中跨多个窗口对行值进行分组,sql,postgresql,subquery,postgresql-8.4,Sql,Postgresql,Subquery,Postgresql 8.4,嗨,基本上我有以下表格结构: 现在,我试着将他们分为以下13周的结束日期,如下所示 例如:如果我们考虑Pay1结束作为产品P1的11/17/2012,我应该能够总结出13周前的速率,并在表中填充13周的列,这是从第16行到第第二十九行的速率之和。我尝试按如下所示编写函数,但由于访问关系时出错,未能成功 create or replace function vin_last_13week_rate(j date,p_name text) RETURNS numeric AS $$ declare

嗨,基本上我有以下表格结构:

现在,我试着将他们分为以下13周的结束日期,如下所示

例如:如果我们考虑Pay1结束作为产品P1的11/17/2012,我应该能够总结出13周前的速率,并在表中填充13周的列,这是从第16行到第第二十九行的速率之和。我尝试按如下所示编写函数,但由于访问关系时出错,未能成功

create or replace function vin_last_13week_rate(j date,p_name text) RETURNS numeric AS $$
declare
week_end date;
rate_tot numeric;
rate_tot_final numeric default 0;
current_week date;
i integer;

begin
week_end:=(j::date - CAST(EXTRACT(DOW FROM j::date)+1 as int))::timestamp +'1 week'::interval+'23 hours'::interval+'59 minutes'::interval+'59 seconds'::interval ;

for i in 1..13 loop
current_week :=week_end - 7;
select total_rate into rate_tot from res where week_end = current_week and product_name = p_name ;

rate_tot_final= rate_tot_final + rate_tot;

end loop;
return rate_tot_final;

end

$$ LANGUAGE plpgsql VOLATILE;

select vin_last_13week_rate(week_end,product_name) from res;
我得到一个错误:函数无法在段上执行,因为它访问关系res
谁能帮我做这个吗。谢谢

如果我理解正确,你需要一个小组。 请试试这个:

SELECT product_name, week_start, sum(week_rate)
FROM <table_name>
GROUP BY product_name, week_start
ORDER BY product_name, week_start

你能告诉我们最终答案应该是什么样子吗?换句话说,你所说的“像智者”在一周内的所有日期、13周内的所有产品、52周内的所有产品都是什么意思?@DanielSparing编辑了我的帖子,现在就清楚地解释了这一点。您现在可以看一下吗好的,首先,您已经从函数体中读取了res,因此在调用时也不需要读取,您可以尝试以下操作并发布错误:选择vin\u last\u 13 Week\u Rate Week\u end,product\u name;是的,它给了我结果,但我的观点是,结果应该与数据一起呈现,这就是我在这里使用“from res”的原因。你的结果是一个数字,你的表格是一个表格。您希望如何组合它们?是否在每行中包含相同值的新列?那就是选择*,选择vin\u last\u 13week\u rate Week\u end,product\u name rate\u tot从现在重新编辑我的帖子。你现在能看一下吗