我得到它。表示从该hours
日期开始的一个月内的小时数。然后,您希望按月添加内容。
下面使用递归 CTE 计算每个月的一天。然后它加入您的表,并选择当前行之前的最新行。最后,它加起来了时间:
declare @fromdate date = '2013-02-01';
declare @todate date = '2013-06-01';
with months as (
select @fromdate as thedate
union all
select DATEADD(month, 1, thedate)
from months
where DATEADD(month, 1, thedate) <= @todate
),
t as (
select 1 as id, CAST('2013-02-01' as DATE) as datefrom, 6 as hours union all
select 2, '2013-04-01', 8
)
select SUM(hours)
from (select t.*, m.thedate, ROW_NUMBER() over (partition by m.thedate order by t.datefrom desc) as seqnum
from months m join
t
on m.thedate >= t.datefrom
) t
where seqnum = 1;