select
sum(
(
((period_str<='$date_str')*(DATEDIFF(period_end, '$date_str')+1))+
(('$date_end'<=period_end)*(DATEDIFF('$date_end', period_str)+1))+
(('$date_str'<=period_str and period_end<='$date_end')*(DATEDIFF(period_end,period_str)+1))
) * baht
) as total
from table
where (period_str between '$date_str' and '$date_end')
or (period_end between '$date_str' and '$date_end')
or ('$date_str' between period_str and period_end)
or ('$date_end' between period_str and period_end)
select sheet_id,
(period_str<='2015-10-30')*(DATEDIFF(period_end, '2015-10-30')+1) first_period,
('2015-11-02'<=period_end)*(DATEDIFF('2015-11-02', period_str)+1) last_period,
('2015-10-30'<=period_str and period_end<='2015-11-02')*(DATEDIFF(period_end,period_str)+1) mid_period,
baht
from (
select 1 sheet_id, '2015-07-01' period_str, '2015-10-31' period_end, 2200 baht union all
select 2 , '2015-11-01' , '2015-12-19' , 2700 union all
select 3 , '2015-12-20' , '2016-01-10' , 3200 union all
select 4 , '2016-01-16' , '2016-04-11' , 2700 union all
select 5 , '2016-04-12' , '2016-04-14' , 3200 union all
select 6 , '2016-04-15' , '2016-04-31' , 2700 union all
select 7 , '2016-05-01' , '2016-10-31' , 2200
) as tb
where (period_str between '2015-10-30' and '2015-11-02')
or (period_end between '2015-10-30' and '2015-11-02')
or ('2015-10-30' between period_str and period_end)
or ('2015-11-02' between period_str and period_end)