我有一个名为 trades
的表,用于保存具有以下架构的货币交易数据:
id - uuid
timestamp - timestamp without time zone
price - numeric
我希望能够以构建蜡烛图的方式进行查询。为此,我需要第一个价格、最后一个价格、最高价格和最低价格,按以下方式分组时间间隔。到目前为止我有这个:
CREATE FUNCTION ts_round( timestamptz, INT4 ) RETURNS TIMESTAMPTZ AS $$
SELECT 'epoch'::timestamptz
+ '1 second'::INTERVAL * ( $2 * ( extract( epoch FROM $1 )::INT4 / $2 ) );
$$ LANGUAGE SQL;
SELECT ts_round( timestamp, 300 ) AS interval_timestamp
, max(price) AS max, min(price) AS min
FROM trades
GROUP BY interval_timestamp
ORDER BY interval_timestamp DESC
如何获取这些时间间隔内的第一个价格和最后一个价格?
最佳答案
我认为这是你想要的查询:
SELECT ts_round( timestamp, 300 ) AS interval_timestamp,
max(firstprice) as firstprice,
max(lastprice) as lastprice,
max(price) AS maxprice, min(price) AS minprice
FROM (SELECT t.*,
first_value(price) over (partition by ts_round(timestamp, 300) order by timestamp) as firstprice,
first_value(price) over (partition by ts_round(timestamp, 300) order by timestamp desc) as lastprice
FROM trades t
) t
GROUP BY interval_timestamp
ORDER BY interval_timestamp DESC;
关于sql - 在时间间隔内选择第一行和最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27954206/