Scratching my head over this one. I am trying to Sum all t1.sales and group into a generated time series of 48 periods in the next 3 days. However my attempt below is returning incorrect results.
SELECT
seq.date,
hh.period,
sum(t1.sales)
From
(select date(date)from generate_series(current_date,current_date + '3 days'::interval ,'1 day'::interval) date)as seq
cross join (select period from generate_series (1,48) period) hh
Left join tbl_look t1
ON (
seq.date between t1.from_date and t1.to_date
and hh.period between t1.from_period and t1.to_period)
Example of the tbl_look, see that period 33 has two rows. I need the sum to capture the 'to_period' when present. In the example below to_period 33 should sum to 13.5, and to_period 34 should = 17.8.
from_date to_date ;from_period; to_period; sales
"2016-12-19" "2016-12-19" ;33 ; 48 ; 5.000
"2016-12-19" "2016-12-19" ;33 ; ; 8.500
"2016-12-19" "2016-12-19" ;34 ; ; 12.800
"2016-12-19" "2016-12-19" ;35 ; ; 16.000
"2016-12-19" "2016-12-19" ;36 ; 38 ; 17.450
"2016-12-19" "2016-12-19" ;37 ; ; 17.850
"2016-12-19" "2016-12-19" ;38 ; ; 17.400
Expected results
seq.results hh.period sales
"2016-12-19" 33 13.5
"2016-12-19" 34 17.8
"2016-12-19" 35 21
"2016-12-19" 36 22.45
"2016-12-19" 37 40.3
"2016-12-19" 38 39.85
"2016-12-19" 39 5
"2016-12-19" 40 5
......