Write a query to perform time-series data analysis on sales data.
Instruction: Use PostgreSQL products(id integer PRIMARY KEY) and sales(sale_date date, product_id integer, amount numeric NOT NULL). Every listed product is active throughout January 1–10, 2026; the feed is complete and no sales row on a day means zero sales. Multiple transactions can occur on a day. Return each product's mean daily sales over the current day and previous six calendar days, for January 7–10 inclusive.
Updated
Official answer
Aggregate transactions to one total per product and calendar day, then create the complete calendar before applying a seven-row window. Under the stated complete-data assumption, a missing sales day means zero sales.
WITH dates AS (
SELECT DATE '2026-01-01' + day AS sale_date
FROM generate_series(0, 9) AS g(day)
), daily AS (
SELECT product_id, sale_date, SUM(amount) AS total
FROM sales
WHERE sale_date >= DATE '2026-01-01'
AND sale_date < DATE '2026-01-11'
GROUP BY product_id, sale_date
), rolling AS (
SELECT p.id AS product_id, d.sale_date,
AVG(COALESCE(s.total, 0)) OVER (
PARTITION BY p.id ORDER BY d.sale_date
ROWS BETWEEN 6 PRECEDING AND CURRENT ROW
) AS seven_day_average
FROM products AS p
CROSS JOIN dates AS d
LEFT JOIN daily AS s
ON s.product_id = p.id AND s.sale_date = d.sale_date
)
SELECT product_id, sale_date, seven_day_average
FROM rolling
WHERE sale_date >= DATE '2026-01-07'
ORDER BY product_id, sale_date;
The displayed January 7 value averages January 1–7 inclusive. Filtering before the window would remove needed history. Multiple transactions on one date are summed first, and every displayed window contains seven calendar days.
Do not replace missing observations with zero when they represent an incomplete feed or an inactive product. Resolve that business meaning first. For timestamp inputs, define the business timezone before deriving the sales date.