select 房屋代码, sum(租金) as 租金 from (select 房屋代码, case
when ('2019-02-01' BETWEEN 月租金起始日期 and 月租金截止日期) and '2019-10-31' > 月租金截止日期 then (月租金 * (datediff(month,'2019-02-01',月租金截止日期)+1))
when ('2019-02-01'< 月租金起始日期 and '2019-10-31' > 月租金截止日期) then (月租金 * (datediff(month,月租金起始日期,月租金截止日期)+1))
when ('2019-10-31' BETWEEN 月租金起始日期 and 月租金截止日期) and '2019-02-01' < 月租金起始日期 then (月租金 * (datediff(month,月租金起始日期,'2019-10-31')+1)) else (月租金 * (datediff(month,'2019-02-01','2019-10-31')+1)) end as 租金 from {合同月租金} where 房屋代码='405304' and (月租金起始日期 >= #2019-02-01# and 月租金起始日期 <= #2019-10-31#) or (截月租金截止日期 >= #2019-02-01# and 月租金截止日期 <= #2019-10-31#) ) as a group by 房屋代码