计算PostgreSQL中的移动天气统计数据

时间:2016-10-25 03:18:59

标签: sql postgresql window-functions

我正在尝试在PostgreSQL天气数据表中计算自上次下雨以来的天数以及该事件中每天的降雨量。我一直试图通过窗口函数实现这一点,但是范围的限制必须是无限制的,这让我有点陷入如何继续。 这是我到目前为止的查询:

SELECT
        station_num,
        ob_date,
        rain,
        max(rain) OVER (PARTITION BY station_num ORDER BY ob_date ASC RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as prev_rain_mm,
        '' as days_since_rain --haven't attempted this calculation yet
FROM
        obs_daily_ground_moisture

这导致以下结果:

postgres result

但我正在努力实现更像这样的事情:

needed postgres result (edited manually)

我觉得所有的部件都与窗户功能范围有关。过滤和嵌套查询,但我不知道如何将它们全部拉到一起。此外,上述数据只是实际数据集的一个子集,整个数据集只有超过五十万行。

2 个答案:

答案 0 :(得分:1)

这里的关键是将观察从第一次出现降雨> 0值开始分组到下一次出现降雨> 0值。此后,您可以使用窗口函数来计算所需的列。

select 
x.station_num,
x.ob_date, 
max(rain) over(partition by station_num,col) prev_rain,
case when rain > 0 then 0 
else row_number() over(partition by station_num, col order by ob_date)-1 end days_since_rain
from (select t.*,
      sum(case when rain > 0 then 1 else 0 end) over(partition by station_num order by ob_date) col 
      from t) x

Sample Demo

答案 1 :(得分:-1)

试试这个。

        DECLARE @Rain  AS FLOAT

        UPDATE A
        SET
        @Rain = CASE WHEN A.Rain = 0 THEN @Rain ELSE A.Rain END,
        A.Rain = CASE WHEN @Rain IS NULL OR A.Rain <> 0 THEN A.Rain ELSE @Rain END
        FROM obs_daily_ground_moisture A

        SELECT ob_date, Rain, 
        max(rain) OVER (PARTITION BY station_num ORDER BY ob_date ASC RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) as prev_rain_mm,
        ROW_NUMBER() OVER(PARTITION BY Rain ORDER BY ob_date) - 1  as days_since_rain
        FROM obs_daily_ground_moisture ORDER BY ob_date