选择时间间隔内的第一行和最后一行

Mat*_*dle 3 sql postgresql aggregate-functions greatest-n-per-group window-functions

我有一个名为trades保存货币交易数据的表,其架构如下:

id        - uuid
timestamp - timestamp without time zone
price     - numeric
Run Code Online (Sandbox Code Playgroud)

我希望能够以构建蜡烛图的方式进行查询。为此,我需要第一个价格最后一个价格最高价格最低价格,并按时间间隔分组。到目前为止我有这个:

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
Run Code Online (Sandbox Code Playgroud)

如何获得这些区间内的第一个价格最后一个价格?

Gor*_*off 5

我认为这是您想要的查询:

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;
Run Code Online (Sandbox Code Playgroud)