I am looking to aggregate data by the end date of a data set with some leading period rather than start. For example, I want to query a table and return the number of matching results 30 days of PRIOR before the end date of the date specified in the results. The source table will ONLY contain the sale date (timestamp). Example:
sales_timestamp ------------------ 2015-08-05 12:00:00 2015-08-06 13:00:00 2015-08-25 12:31:00 2015-08-26 01:02:00 2015-08-27 02:03:00 2015-08-29 04:23:00 2015-09-01 12:00:00 2015-09-02 12:00:00 2015-09-08 00:00:00
An example of a query result as a result :
date_period | count_of_sales -------------------------------- 2015-08-24 | 2 2015-08-31 | 6 2015-09-07 | 6
in which the period_date 2015-09-07 will mean that the company sold 6 items in 30 days END ON 9/7/2015 (and starting on ~ 8/7/2015, if the true 30-day period).
I played with variations of the date_trunc()
function, but it seemed that I could not force the truncation to be applied at the end date , and not grouped at the beginning.
This data will be posted on PostgreSQL 9.1.
source share