在Why Use TimescaleDB over Relational DBs?文章中,给出了针对双时态用例的以下示例
SELECT
time_bucket('1 day', time) AS day,
asset_code,
last(price, time_recorded)
FROM prices
WHERE time > '2017-01-01'
GROUP BY day, asset_code
ORDER BY day DESC, asset_code;
如果我们假设prices
表包含recorded_by列,是否可以编写一个同时返回time_recorded和recorded_by列的查询?
例如,给出以下输入:
+------------------+------------+-------+------------------+-------------+
| time | asset_code | price | time_recorded | recorded_by |
+------------------+------------+-------+------------------+-------------+
| 2019-08-08 12:00 | 1 | 9 | 2019-08-08 12:00 | foo |
| 2019-08-09 15:30 | 1 | 10 | 2019-08-09 15:30 | foo |
| 2019-08-08 12:00 | 1 | 9.5 | 2019-08-09 15:00 | bar |
+------------------+------------+-------+------------------+-------------+
您期望获得以下输出:
+------------+------------+-------+------------------+-------------+
| day | asset_code | price | time_recorded | recorded_by |
+------------+------------+-------+------------------+-------------+
| 2019-08-09 | 1 | 10 | 2019-08-09 15:30 | foo |
| 2019-08-08 | 1 | 9.5 | 2019-08-09 13:00 | bar |
+------------+------------+-------+------------------+-------------+
答案 0 :(得分:1)
事实证明,您实际上可以使最后一个函数的两个参数都引用同一列,例如
SELECT
time_bucket('1 day', time) AS day,
asset_code,
last(price, time_recorded) AS price,
last(time_recorded, time_recorded) AS time_recorded,
last(recorded_by, time_recorded) AS recorded_by
FROM prices
WHERE time > '2017-01-01'
GROUP BY day, asset_code
ORDER BY day DESC, asset_code;