How to get sum of last previous X days of everyday? Let's say I have sales number of last 60 days. How would like to get sum of every last X days of everyday.

For example my graph will include 


Sum of Day - 60 to 30  
Sum of Day - 59 to 29  
Sum of Day - 58 to 28 
Sum of Day - 57 to 27 


......


Sum of Day - 33 to 3
Sum of Day - 32 to 2
Sum of Day - 31 to 1


So that it will give me 4 results ( Day 8 to 4, Days 7 to 3, Day 6 to 2, Day 5 to 1 ). It will be sum of number_of_sales

CREATE TABLE sales (
  sales_id          int  PRIMARY KEY,
  sales_create_date timestamp,
  number_of_sales   int
);

INSERT INTO sales (sales_id, sales_create_date,number_of_sales) 
VALUES
  (0, '2015-05-02 05:30:40',100),
  (1, '2015-05-02 00:00:00',200),
  (2, '2015-05-03 00:00:00',300),
  (3, '2015-05-03 00:00:00',400),
  (4, '2015-05-05 00:00:00',500),
  (5, '2015-05-06 00:00:00',600),
  (6, '2015-05-07 00:00:00',700),
  (7, '2015-05-08 00:00:00',800),
  (8, '2015-05-08 00:00:00',900);


This is the final result that I need from this query


In my real case, I will get sales of last 60 days, and it will return me 30 records but summing up previous 30 days every day. In example I gave you rather than analyzing 60 days, I analyzed 8 days, which will product me 4 entries.
Plase don't spend time by getting the date of last entry. Just think the start date is today always.
Here is what I think you want,

SELECT days.d::date, sum(sales.number_of_sales)
FROM (
        SELECT min(sales_create_date::date), max(sales_create_date::date)
        FROM sales
) AS minmax
CROSS JOIN LATERAL generate_series(minmax.min, minmax.max, '2 days')
        AS days(d)
LEFT OUTER JOIN sales
        ON sales_create_date &gt;= days.d
        AND sales_create_date &lt; (days.d + '2 days')
GROUP BY days.d;


Notice you have to put the window date twice in the above.

What we're doing is,


Selecting min and max dates for the table
Generating the start for the range on the window
Joining back to sales with the range start and the end interval
Grouping and selecting the count(*) in the window.


Result,

     d      | sum  
------------+------
 2015-05-02 | 1000
 2015-05-04 |  500
 2015-05-08 | 1700
 2015-05-06 | 1300
(4 rows)