SELECT '2010-01-01 01:00:00'::DATE + (m || ' minute')::INTERVAL, v, p
FROM generate_series(0, 59) m
LEFT JOIN
table1 t1
ON t1.t >= '2010-01-01 01:00:00'::DATE + (m || ' minute')::INTERVAL
AND t1.t < '2010-01-01 01:00:00'::DATE + (m + 1 || ' minute')::INTERVAL
LEFT JOIN
table2 t2
ON t2.t >= '2010-01-01 01:00:00'::DATE + (m || ' minute')::INTERVAL
AND t2.t < '2010-01-01 01:00:00'::DATE + (m + 1 || ' minute')::INTERVAL
這裏假設記錄在每一分鐘內都是唯一的(雖然秒數可能會有所不同)。
如果他們不是,你會收到重複。
在這種情況下,你可能要對其進行聚合(比如,總和):
SELECT '2010-01-01 01:00:00'::DATE + (m || ' minute')::INTERVAL,
COALESCE
(
SELECT SUM(p)
FROM table1 t1
WHERE t1.t >= '2010-01-01 01:00:00'::DATE + (m || ' minute')::INTERVAL
AND t1.t < '2010-01-01 01:00:00'::DATE + (m + 1 || ' minute')::INTERVAL
), 0) p,
COALESCE
(
SELECT SUM(v)
FROM table2 t2
WHERE t2.t >= '2010-01-01 01:00:00'::DATE + (m || ' minute')::INTERVAL
AND t2.t < '2010-01-01 01:00:00'::DATE + (m + 1 || ' minute')::INTERVAL
), 0) v
FROM generate_series(0, 59) m
是時間戳每個給定分鐘內是唯一的?秒鐘可以變化嗎? – Quassnoi 2010-11-02 13:32:30