I have a table that tracks changes in stocks through time for some stores and products. The value is the absolute stock, but we only insert a new row when a change in stock
This is rather quick&dirty: instead of doing the nasty interval arithmetic, just join to a calendar-table and sum them all.
WITH calendar(zdate) AS ( SELECT generate_series('2013-01-01'::date, '2013-01-15'::date, '1 day'::interval)::date )
SELECT st.store_id,st.product_id
, SUM(st.zvalue) AS sval
, COUNT(*) AS nval
, (SUM(st.zvalue)::decimal(8,2) / COUNT(*) )::decimal(8,2) AS wval
FROM calendar
JOIN stocks st ON calendar.zdate >= st.zdate
AND NOT EXISTS ( -- this calendar entry belongs to the next stocks entry
SELECT * FROM stocks nx
WHERE nx.store_id = st.store_id AND nx.product_id = st.product_id
AND nx.zdate > st.zdate AND nx.zdate <= calendar.zdate
)
GROUP BY st.store_id,st.product_id
ORDER BY st.store_id,st.product_id
;