postgresql循环,用于一周内的最大累积降雨量

时间:2014-07-21 14:04:33

标签: sql postgresql

我想要从1994年到2005年的数据降雨量(每小时一个数据)。我想通过使用sql计算一周的最大累积量。从数百万的数据中,我必须选择第一周(168小时)的数据,然后我必须将数据从1-24小时,2到25小时等等总和到168,并选择这145个总和的最大值是第一周最大累积降雨量的数据。 然后返回桌面并继续接下来的168小时。

CREATE OR REPLACE FUNCTION maxcrain() RETURNS numeric AS $BODY$
declare a int;
declare b int;
declare c int;
declare temp int;
begin
    while id <= b + 145 loop
begin

    while id <= a + 24 loop
begin

    if rain > 0 then

        c := 0;
        c = c + rain
        id = id + 1


    else
        id = id + 1
        continue
end

        a = a + 1

        id = a

        if (c > temp)
        temp = c
        update maxcrain = temp
end loop

        b = id + 23
end loop;

$BODY$

LANGUAGE 'plpgsql' ;

1 个答案:

答案 0 :(得分:1)

使用窗口函数执行此操作!

select week, max(hr24value)
from (select rf.*,
             floor(rf.hour/168) as week,
             sum(rf.value) over (partition by week
                                 order by hour
                                 rows between 23 preceding and current row
                                ) as hr24value
      from rainfall rf
     ) rf
group by week;

如果您的Postgres版本不支持该rows子句,请使用累计金额lag()

select week, max(hr24value)
from (select rf.*,
             (cumvalue - lag(cumvalue) over (partition by week order by hour)
             ) as hr24value
      from (select rf.*,
                   floor(rf.hour/168) as week,
                   sum(rf.value) over (partition by floor(rf.hour/168) 
                                       order by hour
                                      ) as cumvalue
            from rainfall rf
           ) rf
     ) rf
group by week;