你如何在Postgres中预先形成GROUP BY分钟声明?我也想知道如果有记录缺少怎么用零替换缺失?
SELECT avg(load) as load, min(created_at) as create_at FROM stats GROUP BY ?what here?
那么我会得到如下行:
created_at | load
27.3.2013 16:08 | 15
27.3.2013 16:09 | 14
27.3.2013 16:10 | 16
27.3.2013 16:12 | 15
缺少一条记录,请注意
27.3.2013 16:11 | 0
如何设置默认值或如何调用?
答案 0 :(得分:1)
您需要加入一个包含所需分钟数的集合。您可以使用generate_series(start,stop,step)。是这样的:
SELECT avg(load), min(created_at) as load
FROM generate_series('2013-3-20 0:00:00'::timestamp, '2013-3-30 0:00:00',
'1 minute') AS minutes(minute)
LEFT JOIN stats ON minute=date_trunc('minute', stats.created_at)
GROUP BY minute