Função de janela PostgreSQL com LIMIT
-
22-12-2019 - |
Pergunta
A consulta abaixo agrupa os resultados de first
em 4 caixas de datas igualmente espaçadas e agrega uma média para the_value
em cada caixa.
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;
Eu gostaria de poder calcular apenas a média para o valor mais baixo, digamos 20 the_value
está em cada caixa.De outros posts aqui no Stackoverflow vi que isso é possível e que talvez ORDER BY the_value
e rank()
é a melhor maneira de fazer isso.Mas minha dificuldade é que não tenho certeza de onde minha consulta atual deve ser modificada para implementar isso.
Qualquer visão seria apreciada.
Postgre versão 9.3
Solução
Usar row_number()
em cada caixa.
Primeiro calcule o número da linha rn
, então aplique WHERE rn < 21
na próxima etapa:
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;
CTEs y
e z
poderiam ser confundidos.De forma similar first
e x
poderiam ser confundidos.
Mas é mais claro assim.
Não testado, pois não temos dados de teste.