这是一个SQL代码的高尔夫球帖子...
我有一个表,其中包含一个时间戳,一个标识符和一个价格
CREATE TABLE IF NOT EXISTS ts_data (
ts TIMESTAMP WITHOUT TIME ZONE, --timestamp
metric INTEGER, --identifier
usd DOUBLE PRECISION -- price
);
给出示例数据:
INSERT INTO ts_data (ts, metric, usd)
VALUES
('2018-08-21 01:00:00', 1, 5.00),
('2018-08-21 01:05:00', 1, 10.00),
('2018-08-21 01:10:00', 1, 15.00),
('2018-08-21 01:15:00', 1, 20.00),
('2018-08-21 02:00:00', 1, 25.00),
('2018-08-21 02:05:00', 1, 30.00),
('2018-08-21 02:10:00', 1, 35.00),
('2018-08-21 02:15:00', 1, 40.00),
('2018-08-21 01:00:00', 2, 1.00),
('2018-08-21 01:05:00', 2, 2.00),
('2018-08-21 01:10:00', 2, 3.00),
('2018-08-21 01:15:00', 2, 4.00),
('2018-08-21 02:00:00', 2, 5.00),
('2018-08-21 02:05:00', 2, 6.00),
('2018-08-21 02:10:00', 2, 7.00),
('2018-08-21 02:15:00', 2, 8.00);
我要做什么
此查询完成了我想要的
SELECT ts, SUM(usd) as usd FROM (
SELECT metric, date_trunc('HOUR', ts) as ts, AVG(usd) AS usd
FROM ts_data
WHERE ts BETWEEN '2018-08-20 00:00:00' AND '2018-08-22 00:00:00'
AND metric IN (1, 2)
GROUP BY date_trunc('HOUR', ts), metric
) samples
GROUP BY ts;
我们得到:
+------------------------------+
| ts | price|
+------------------------------+
| "2018-08-21 01:00:00" | 15 |
| "2018-08-21 02:00:00" | 39 |
有没有更有效或紧凑的方法来完成同一件事?