Pir*_*App 4 sql postgresql greatest-n-per-group timescaledb
我有一张桌子
| Asset | timestamp | open | high | low | close | volume |
|-------|---------------|------|------|-----|-------|--------|
| AAPL | 1551274920000 | 200 | 300 | 200 | 250 | 10240 |
| AAPL | 1551274980000 | 201.4| 299.5| 200 | 244.5 | 11871 |
| GOOG | 1551274980000 | 471.2| 488.2|464.6| 474.84| 5476.58|
Run Code Online (Sandbox Code Playgroud)
如何获取每个资产的最新时间戳。这是我到目前为止所尝试的
方法一
SELECT symbol, max(ts) from ohlc_60 group by symbol;
This seems to scan all the chunks
explain select symbol, max(ts) from ohlc_60 group by symbol;
QUERY PLAN
--------------------------------------------------------------------------------------
HashAggregate (cost=1199.37..1201.37 rows=200 width=16)
Group Key: ohlc_60.symbol
-> Append (cost=0.00..1014.27 rows=37019 width=16)
-> Seq Scan on binance_ohlc_60 (cost=0.00..0.00 rows=1 width=40)
-> Seq Scan on _hyper_67_199_chunk (cost=0.00..197.81 rows=8681 width=15)
-> Seq Scan on _hyper_67_200_chunk (cost=0.00..284.32 rows=13032 width=15)
-> Seq Scan on _hyper_67_201_chunk (cost=0.00..281.14 rows=12414 width=15)
-> Seq Scan on _hyper_67_202_chunk (cost=0.00..48.41 rows=2141 width=15)
-> Seq Scan on _hyper_67_203_chunk (cost=0.00..17.50 rows=750 width=40)
(9 rows)
Run Code Online (Sandbox Code Playgroud)
我目前将 1m 数据存储为 1 小时的块,但可能会将它们变成 1 天的块。我需要获取每个资产的最后时间戳而不进行顺序扫描,有什么建议非常感谢吗?
您的查询应该从以下索引中受益匪浅:
CREATE INDEX idx ON ohlc_60 (symbol, ts);
Run Code Online (Sandbox Code Playgroud)
这应该起作用的原因是您要求每个组的时间戳的最大值symbol。这可以通过 B 树的扫描轻松获得。
| 归档时间: |
|
| 查看次数: |
2104 次 |
| 最近记录: |