I have the following table.
Column | Type | Collation | Nullable | Default
----------+-----------------------------+-----------+----------+---------
code | text | | not null |
price_at | timestamp without time zone | | not null |
price | double precision | | not null |
I need to use the data in this table to create a candlestick chart that will have 6-hour candlesticks. Each candlestick is represented by the fields
{ x, open, close, low, high }
where x is the UNIX timestamp of the beginning of the period.
The following query works, but using distinct
causes the query to take longer. Usually, when people don't want to use distinct, they use group by
instead, but I can't use that with the window functions and I'm not sure it would help anyway. Is there a way to eliminate the use of distinct in this query to make it faster and still return the same results?
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
Asked by Zephyrus
(283 rep)
Nov 14, 2023, 04:55 PM
Last activity: Nov 15, 2023, 12:55 PM
Last activity: Nov 15, 2023, 12:55 PM