sql >> Base de Datos >  >> RDS >> PostgreSQL

Múltiples promedios en intervalos uniformemente espaciados

Sugiero la práctica función width_bucket() :

Para obtener el promedio de cada segmento de tiempo ("bin"):

SELECT width_bucket(extract(epoch FROM t.the_date)
                  , x.min_epoch, x.max_epoch, x.bins) AS bin
     , avg(value) AS bin_avg
FROM   tbl t
    , (SELECT extract(epoch FROM min(the_date)) AS min_epoch
            , extract(epoch FROM max(the_date)) AS max_epoch
            , 10 AS bins
       FROM   tbl t
      ) x
GROUP  BY 1;

Para obtener el "promedio móvil" sobre el intervalo de tiempo creciente (paso a paso):

SELECT bin, round(sum(bin_sum) OVER w /sum(bin_ct) OVER w, 2) AS running_avg
FROM  (
   SELECT width_bucket(extract(epoch FROM t.the_date)
                     , x.min_epoch, x.max_epoch, x.bins) AS bin
        , sum(value) AS bin_sum
        , count(*)   AS bin_ct
   FROM   tbl t
       , (SELECT extract(epoch FROM min(the_date)) AS min_epoch
               , extract(epoch FROM max(the_date)) AS max_epoch
               , 10 AS bins
          FROM   tbl t
         ) x
   GROUP  BY 1
   ) sub
WINDOW w AS (ORDER BY bin)
ORDER  BY 1;

Usando the_date en lugar de date como nombre de columna, evitando palabras reservadas como identificadores.
Desde width_bucket() actualmente solo está implementado para double precision y numeric , extraigo valores de época de the_date . Detalles aquí:
Agregar nubes de puntos de coordenadas (x,y) en PostgreSQL