PostgreSQL group by 24 hour period noon to noon

2019-08-09 10:58发布

问题:

Using PostgreSQL I need to be able to aggregate data, as the title suggests, in 24 hour periods but from noon to noon. The data is collected every 5 minutes over a period of several weeks and I want to average the readings over 24 hour periods from 12:00 noon of first day to 12:00 noon of the next day until the end of the data.

For a more standard midnight to midnight grouping I can use the example below, which works just fine, but I can't see work out how to adapt this to the noon-noon time-span I need.

group by date_trunc('day', <DateCol>)

PostgreSQL is relatively new to me, and if I was going to do this in SQL Server I'd use:

dateadd(hour, (datepart(hour, <DateCol>)/12)*12, dateadd(day, 0, datediff(day, 0, <DateCol>)))

As far as I can tell from reading the documentation at http://www.postgresql.org there is no equivalent to date add. Is there a way to do what is required within PostgreSQL?

回答1:

Try grouping by day on date - 12hours:

group by date_trunc('day', <DateCol> - INTERVAL '12 hours')