Eu tenho a seguinte tabela.
Column | Type | Collation | Nullable | Default
----------+-----------------------------+-----------+----------+---------
code | text | | not null |
price_at | timestamp without time zone | | not null |
price | double precision | | not null |
Preciso usar os dados desta tabela para criar um gráfico de velas que terá velas de 6 horas. Cada vela é representada pelos campos { x, open, close, low, high }
onde x é o timestamp UNIX do início do período.
A consulta a seguir funciona, mas usar distinct
faz com que a consulta demore mais. Normalmente, quando as pessoas não querem usar distinto, elas usam group by
, mas não posso usar isso com as funções da janela e não tenho certeza se isso ajudaria de qualquer maneira. Existe uma maneira de eliminar o uso de distinto nesta consulta para torná-la mais rápida e ainda retornar os mesmos resultados?
with price_quotes as (
select
extract (epoch from price_at) - (extract (epoch from price_at) % extract (epoch from '6 hours'::interval)) as period_begin,
extract (epoch from price_at) as quote_time,
price
from quote)
select distinct
period_begin as x,
first_value (price) over (partition by period_begin order by quote_time asc) as open,
last_value (price) over (partition by period_begin order by quote_time asc rows between current row and unbounded following) as close,
min (price) over (partition by period_begin) as low,
max (price) over (partition by period_begin) as high
from price_quotes
order by x asc