sql - 在时间间隔内选择第一行和最后一行

标签 sql postgresql aggregate-functions greatest-n-per-group window-functions

我有一个名为 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/

相关文章:

sql - 查询孤立关系

sql - 使用 group by 聚合 sql 中的日期时间

python - 如何检索 panda 分组数据框中的聚合值

c - postgresql c 自定义函数中的奇怪行为

windows - Docker PostgreSQL:无法连接到Windows 7上的服务器

postgresql - 如何防止 postgres View 调用冗余函数

sql - 想要对某些字段求和而对其他字段求和 SQL

SQL代理作业: Determine how long it has been running

sql - Bigquery - json_extract 从数组中提取所有元素

c# - 在 LINQ to SQL 中执行查询