Domanda

La query sottostante raggruppa i risultati da first in 4 bidoni da date ugualmente distanziati e aggregati una media di the_value in ciascun cestino.

WITH first as(
SELECT
    extract(EPOCH FROM foo.t_date) as the_date,
    foo_val as the_value
FROM bar
INNER JOIN foo
ON
    foo.user_id = bar.x_id
    and
    foo.user_name = 'xxxx'
)
SELECT bin, round(sum(bin_sum) OVER w /sum(bin_ct) OVER w, 2) AS running_avg
FROM  (
   SELECT width_bucket(first.the_date
                     , x.min_epoch, x.max_epoch, x.bins) AS bin
        , sum(first.the_value) AS bin_sum
        , count(*)   AS bin_ct
   FROM   first
       , (SELECT MIN(first.the_date) AS min_epoch
               , MAX(first.the_date) AS max_epoch
               , 4 AS bins
          FROM  first
         ) x
   GROUP  BY 1
   ) sub
WINDOW w AS (ORDER BY bin)
ORDER  BY 1;
.

Vorrei essere in grado di calcolare solo la media per il più basso dire 20 the_value in ogni cestino.Da altri messaggi qui su Stackoverflow ho visto che questo è possibile e che forse ORDER BY the_value e rank() è il modo migliore per farlo.Ma la mia lotta è che non sono sicuro di dove dovrebbe essere modificata la mia query corrente per implementare questo.

Qualsiasi intuizione sarebbe apprezzata.

Postgres versione 9.3

È stato utile?

Soluzione

Utilizzare row_number() su ciascun bin.
Prima calcolare il numero di riga rn, quindi applica WHERE rn < 21 nel passaggio successivo:

WITH first AS (
   SELECT extract(EPOCH FROM foo.t_date) AS the_date
        , foo_val AS the_value
   FROM bar
   JOIN foo ON foo.user_id = bar.x_id
           AND foo.user_name = 'xxxx'
   )
, x AS (
   SELECT MIN(the_date) AS min_epoch
        , MAX(the_date) AS max_epoch
   FROM  first
   )
, y AS (
   SELECT width_bucket(f.the_date, x.min_epoch, x.max_epoch, 4) AS bin, *
   FROM   first f, x
   )
, z AS (
   SELECT row_number() OVER (PARTITION BY bin ORDER BY the_value) AS rn, *
   FROM   y
   )
SELECT bin, round(sum(bin_sum) OVER w / sum(bin_ct) OVER w, 2) AS running_avg
FROM  (
   SELECT bin
        , sum(the_value) AS bin_sum
        , count(*)       AS bin_ct
   FROM   z
   WHERE  rn < 21   -- max 20 lowest values
   GROUP  BY 1
   ) sub
WINDOW w AS (ORDER BY bin)
ORDER  BY 1;
.

cte y e z potrebbero essere conflitti.Allo stesso modo first e x potrebbero essere conflitti.
Ma è più chiaro in questo modo.

Non testato, dal momento che non abbiamo dati di prova.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top