Postgres查询将15分钟间隔转换为每小时间隔

时间:2015-01-30 21:13:26

标签: sql postgresql date

我想将postgres数据库中的15分钟间隔表转换为每小时间隔,并将其他列中的所有值相加。我该怎么做呢?查询会是什么?

示例:

timestamp                    count
"2015-01-05 12:00:00"          35
"2015-01-05 12:15:00"       45
"2015-01-05 12:30:00"       23
"2015-01-05 12:45:00"       23
"2015-01-05 01:00:00"       45
"2015-01-05 01:15:00"       12
"2015-01-05 01:30:00"       11
"2015-01-05 01:45:00"        56

我希望输出表是

timestamp                  count
2015-01-05 12:00:00         126
2015-01-05 01:00:00         124

2 个答案:

答案 0 :(得分:2)

简单,在PostgreSQL中:

SELECT date_trunc('hour', timestamp_col) as ts_hour, sum(count_col) 
FROM counts_table
GROUP BY ts_hour
ORDER BY ts_hour;

答案 1 :(得分:1)

FuzzChef提供了一个很好的答案,但您可能需要将别名从别名更改为实际的date_trunc,如下所示:

SELECT date_trunc('hour', timestamp_col) as ts_hour, sum(count_col) FROM counts_table 
GROUP BY date_trunc('hour', timestamp_col) 
ORDER BY date_trunc('hour', timestamp_col) 
;

此外,如果您只是希望HOUR出现,请使用extract,如下所示:

SELECT extract('hour' from timestamp_col) as ts_hour, sum(count_col) FROM counts_table 
GROUP BY extract('hour' from timestamp_col) 
ORDER BY extract('hour' from timestamp_col) 
;