перепроверь результат только, на коленке написано
declare @rent table(
id int,
rentBegin datetime,
rentEnd datetime,
total decimal(15,2)
)
insert into @rent (id, rentBegin, rentEnd, total) values (1, '2014-12-25 13:30', '2015-01-03 18:00', 5200)
insert into @rent (id, rentBegin, rentEnd, total) values (2, '2015-01-03 18:00', '2015-01-26 12:20', 17340)
insert into @rent (id, rentBegin, rentEnd, total) values (3, '2015-01-26 12:20', '2015-02-07 00:35', 4700)
insert into @rent (id, rentBegin, rentEnd, total) values (4, '2015-12-24 14:45', '2016-01-04 13:00', 6500)
Declare @begin datetime,
@end datetime
Set @begin = '2015-01-01 00:00'
Set @end = '2015-01-31 23:59'
select cast(sum(tariff * perionTime) as decimal(15,2)) from
(
select id, DATEdiff(ss, rentBegin, rentEnd) as fullrentTime,
case
when (rentBegin < @begin and rentEnd > @end) then DATEdiff(ss, @begin, @end)
when (rentBegin >= @begin and rentEnd <= @end) then DATEdiff(ss, rentBegin, rentEnd)
when (rentBegin < @begin and rentEnd <= @end) then DATEdiff(ss, @begin, rentEnd)
when (rentBegin >= @begin and rentEnd > @end) then DATEdiff(ss, rentBegin, @end)
end as perionTime
, total, total / DATEdiff(ss, rentBegin, rentEnd) as tariff from @rent
where rentBegin between @begin and @end or rentEnd between @begin and @end
) as r